Replace a service programatically at runtime in AngularJS

1.2k Views Asked by At

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.

1

There are 1 best solutions below

0
On

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.