Home > Enterprise >  Why constructor of two root service does not work?
Why constructor of two root service does not work?

Time:09-14

Here is two root services:

Service 1:

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private data$ = new BehaviorSubject([]);
  public dataObs$ = this.data$.asObservable();

  constructor(private http: HttpClient) {}

  setData(data: any) {
    this.data$.next(data);
  }

  loadData(url: string, category: number) {
    return this.http.get(`${url}?chapter=${category}`);
  }
}

Service 2:

@Injectable({
  providedIn: 'root',
})
export class ImportExportService {
  private data$: Observable<any>;

  constructor(private dataService: DataService) {
    this.data$ = this.dataService.dataObs$;
    this.data$.subscribe((e) => console.log(e));
    alert('Done');
  }
}

Why constructor of the second service does not work, I dont get message alert('Done');.

Both are registered as root service

CodePudding user response:

Angular create an instance of service only if it's injected somewhere in your components ( or other classes such as guards, pipes, etc ) . if you didn't inject it in any constructor, no insatnce of that service will be created. for more see Angular Docs

  • Related