0

Let us say I have a service named httpservice, and let us say I have some m and n no of controllers and services, where m and n are positive integers and i want to use this service every where.

So my question is "Is there any way/mechanism in angularJs to inject this dependency httpservice only one time for all the different components of my application??"

That means rather than writing code for injecting dependency for every controller and other services/directives/filters etc.

2
  • 1
    suggestions : change service into provider and inject into .run block Commented Jun 22, 2016 at 7:18
  • but i think providers can be injected in the .config() (configuration part) instead of run part Commented Jun 22, 2016 at 8:11

1 Answer 1

1

This sounds like an anti-pattern. It's unlikely a service is really needed in every controller and service of your application.

Following this architecture, you'd find yourself in a situation where the service is available, or 'globally injected', in parts of your application that don't need it. It's beneficial for both readability and performance to be explicit, even if this seems verbose.

This answer (as referenced in another answer) describes a way of almost doing this by attaching a reference variable to the $rootScope, or relying on scope inheritance. However, this means it's only available in yours controllers and views, and not other services / factories – unless you pass in a $scope reference.

Alternatively, and depending on the desired functionality of the service, an object literal attached to the global scope would be behave as if it were injected everywhere. This would be working against the intended design of Angular though.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.