Home > Software engineering >  How can I use service inside other service without providers array and providedIn?
How can I use service inside other service without providers array and providedIn?

Time:11-30

I need to use Service1 inside Service2, but I wouldn't like to use Service1 as Singleton and define it via providers array in a module and providedIn inside service definition.

I would like to use it like on component level, then we use providers array in component decorator.

Is it possible?

import { Injectable } from '@angular/core';

@Injectable()
export class Service1 {
  doSmth(){
  }
}


@Injectable()
export class Service2 {
  doSmth(){
  }
}

And the similar situation, then I need to use "not-singleton" service into Ngrx Effects. How could I do it?

CodePudding user response:

An Injectable must be provided somewhere. Perhaps I am not understanding this completely, but maybe you could remove the Injectable decorator and just use a class constructor to get an instance of the class, since you don't want a singleton instance?

@Injectable()
export class Service2 {
  service1 = new Service1();
}
  • Related