0

How can i add a service to the module/angular app at runtime.

Will $injector or $provide help me?

Something like

app.addService('s',['k',function(k){console.log('new Service k');}]);

1 Answer 1

1

Yes, $provide will do it. See the documentation at https://docs.angularjs.org/api/auto/service/$provide

So you could do something like this (from within foo):

app.factory('foo',functon() {
   $provide.factory('s',function() {
      console.log("new service 's'");
   });
});

The problem is that you cannot inject $provide directly into the service, so you need to capture it at module creation time.

The question is, why would you want to do this? Since the service 's' isn't declared until 'foo' is run, you run the risk of calling the service as a dependency at some other point. If it is anywhere within a normal injection, you would probably get some weird error.

Matter of fact, I think the only way it would work is by using the $injector to get it from within some other service.

So, yes, you could do it, but would you really want to?

Look at this fiddle: http://jsfiddle.net/ch8vu4ng/1/

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.