Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a service programatically at runtime in AngularJS

I want to replace one of the services a web app has at runtime for testing purposes. There is a service that connects to an external service that is not available in some local environments, and I would like to just execute a command to replace it with a mock.

I have seen I can get any service from AngularJS at runtime by calling:

> angular.element('html').injector().get('myService')

But I would like to know if there is a way of replacing that 'myService' with something else.

I know that creating a 'myServiceWrapper' that exposes 'myService' would allow me to replace it easily by doing:

> angular.element('html').injector().get('myServiceWrapper').myService = new Whatever();

But I would like to avoid making changes to an application that is already working.

like image 470
vtortola Avatar asked Mar 26 '26 01:03

vtortola


1 Answers

You have a couple options. First, you could just declare a new service with the same name (after the original service has already been declared). Since Angular currently has no concept of namespacing, your new service will overwrite the old one.

Second, you could use a decorator to modify parts of the service.

Lastly, the ngMockE2E module can also let you swap out the $httpBackend for a mock one, to use the service as it currently exists, but stub out any calls to external providers.

like image 103
Derek Stobbe Avatar answered Mar 28 '26 13:03

Derek Stobbe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!