1

I would like to create a singleton from below class and use the singleton in other files as MyClass.Instance.SomeStatus. I checked several questions and answers on StackOverflow, but it isn't clear yet how to create a singleton which requires a service as parameter (DI). Could you explain the correct way of implementing this case? (Do I need to add MyClass to '@NgModule({' as well?)

Note: I already had a look at this question, but it doesn't explain the DI service parameter.

@Injectable()
export class MyClass {

    public SomeStatus: boolean = false;

    constructor(private _myService:MyService) {
    }

   public DoSomething(): void
   {          
        this._myService.observableEvents.subscribe(result => {
                this.SomeStatus = result;
        });
   }
}

Update 1

@Injectable()
export class AnotherClass{

    constructor(private _myService:MyService, private myClass:MyClass) {
    }
}

In the html file I use: myClass.SomeStatus.

Odrai
  • 2,163
  • 2
  • 31
  • 62
  • 2
    If you inject `MyClass` it's already a singleton -- Angular does this for you as part of its dependency injection. You do have to declare it as a provider in a module where other injectables in the same module will inject it. – Explosion Pills Sep 20 '18 at 16:52
  • @ExplosionPills I was thinking the same, but why is the constructor called multiple times? The SomeStatus is set to false everytime, despite I earlier called the DoSomething method. (Please have a look at 'Update 1'.) – Odrai Sep 20 '18 at 16:53
  • @ExplosionPills Update 1: So class x calls the DoSomething method of MyClass. AnotherClass uses, at a later point in time, the myClass object (DI). myClass.SomeStatus remains false, despite this.SomeStatus is set to true during the call of DoSomething. (Note: I already added MyClass to the providers of @NgModule). – Odrai Sep 20 '18 at 16:57
  • `AnotherClass` will also have to be part of `NgModule` and it has to be injectable as well. – Explosion Pills Sep 20 '18 at 17:35
  • @ExplosionPills Thanks for the suggesting, but unfortunately they are both @Injectable() and added to the providers section of NgModule. ('Update 1' was just pseudo code, I updated the code). For some reason, the constructor of AnotherClass is called multiple times and the SomeStatus is reset to false (as mentioned in my previous comment). – Odrai Sep 20 '18 at 17:38
  • 1
    By any chance could you show us on stackblitz.com – Explosion Pills Sep 20 '18 at 17:43

1 Answers1

0

you can create singletons by either using the providedIn: 'root' flag on the service itself. It will work, regardless whether you use other services as DI or not.

If you use lazy loading of modules/routes you need a different approach, and can use the .forRoot() pattern, to ensure your service is only being initialized once. I just wrote an example that also outlines why lazy loading works differently here https://developapa.com/angular-singleton-service/

Nicolas Gehlert
  • 2,626
  • 18
  • 39