Configuring a service to utilize another service.

36 views
Skip to first unread message

Johnny Hauser

unread,
Mar 31, 2014, 5:40:44 PM3/31/14
to ang...@googlegroups.com
I have a service which I want to be able to configure by passing in a function for it to use. As long as this function returns something my service can use, it doesn't care how it got the data nor sync/async. Here's a sample of what I'd like to be able to do, but will not work for obvious reasons:

.config(function(MyServiceProvider, OtherService) {
 
  MyServiceProvider.setSomeMethod( OtherService.someMethod );

})

That would be awesome, but there doesn't seem to be a way to reference "OtherService" from within the config function. I know this is because "OtherService" could potentially not yet be configured and therefore an instance of it shouldn't exist yet, but then what is a person to do in this circumstance?

In this case, is it *with angst* proper to make this association within a run block?

.run(function(MyService, OtherService) {

  MyService.setSomeMethod( OtherService.someMethod );

})

Johnny Hauser

unread,
Mar 31, 2014, 8:04:16 PM3/31/14
to ang...@googlegroups.com
I posted this on Stack Overflow and a suggestion about $injector got me on the right track. I passed $injector to the service which is to be configured, and had the service pass the $injector to the configured function when it is called. This effectively makes any service available within the config block. Details and code sample here: http://stackoverflow.com/a/22774388/1435655


--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/be5I0XVN71A/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

John Walker

unread,
Apr 1, 2014, 10:54:12 AM4/1/14
to ang...@googlegroups.com
Just curious, why did you not want to do it in the run block?

Johnny Hauser

unread,
Apr 1, 2014, 11:04:59 AM4/1/14
to ang...@googlegroups.com
I'm pretty sure that's just technically wrong to do. It's configuration, so put it in config, right? There's more going on with that StackOverflow post now. The solution I originally posted is not the best choice after all. It would be better to create a wrapper service and pass its name by string to the configuration. See the post for a ton more detail. http://stackoverflow.com/questions/22773087/configuring-a-service-via-its-provider-to-use-another-service
Reply all
Reply to author
Forward
0 new messages