How to destroy injected service in angularjs cache?

904 Views Asked by At

We all know that in AngularJS service are singletons. Since then when you do this $injector.get('foo') you will get an instance of this service and its constructor would be invoked + object would be added into injector's cache for the reason because it is the singleton.

Anyway, are there any methods that I can utilize for removing service in that cache for re-creating service again? Using factory solves this but anyway.

1

There are 1 best solutions below

0
The.Bear On BEST ANSWER

To reset a service, you can expose a function that invoke the service again.

PLUNKER

Service

app.service('MyService', MyService);

function MyService () {
  console.log('init service #' + Date.now());

  this.reset = () => {
    MyService();
  }
}

Then you can use it everywhere like

var myService = $injector.get('MyService');
myService.reset();

With ES6 classes you can do something like this:

class MyService {

  constructor() {
    console.log('init service #' + Date.now());

    this.reset = () => {
      new MyService();
    }
  }
}