Declare AngulaJS service multiple times in the same module

17 views
Skip to first unread message

Andrea Forni

unread,
Oct 26, 2016, 10:29:53 AM10/26/16
to Angular
Hi,
I am working with AngularJS 1.x and I can define the same service multiple times in the same module. Please see this Plunker example.


In the example, I am defining the service "nameService" 2 times in module "myApp". At runtime, AngularJS uses the value returned by the second implementation of the service: "Second Definition".

So, empirically, AngularJS seems to use always the latest definition of a service, ignoring the previous ones.

My question is: is there any official documentation describing this behavior?


I mean, Angular could decide to use always the first definition and discard the others but it decides to use always the latest.  I this behavior documented somewhere in the official AngularJS documentation?

Thank you, regards
Andrea

Sander Elias

unread,
Oct 31, 2016, 12:26:49 AM10/31/16
to Angular
Hi Andrea,

Yes, this is documented somewhere, but I really don't recall the location. sorry.

Angular 1 uses a flat list to do dependency injection. So, if you redefine a something, it simply replaces what is already there. 
The "rule" for that is actually quite simple. The last one gets in. 

However, using modern build tools, and the different way's scripts get loaded, that is not always an easy prediction to make.
Long story cut short, don't use generic/common names. 

Regards
Sander

Message has been deleted

Andrea Forni

unread,
Nov 7, 2016, 8:53:26 AM11/7/16
to Angular
Thank you very much Sander,
I checked the code and I saw the "flat list" for dependency injection and I was searching an official documentation explaining this behavior.

Good point about build tools and inclusion order which may vary. Service redefinition done this way could be very unreliable.

Regards,
Andrea
Reply all
Reply to author
Forward
0 new messages