I created BaseService, CommonService as below and my other services are dependent on this hierarchy. My main intention was to reuse the utilService and cacheService in all my ModuleServices [there are many ModuleServices].
export abstract class BaseService {
public utilService: UtilService;
_listingSubject = new ReplaySubject();
public listingObservable: Observable<QuickList> = this._listingSubject .asObservable();
constructor() {
super();
this.utilService = ServiceLocator.injector.get(UtilService);
}
}
export class CommonService extends BaseService {
public cacheService: CacheService;
constructor() {
super();
this.cacheService = ServiceLocator.injector.get(CacheService);
}
}
export class ModuleServiceA extends CommonService {
constructor() {
super();
}
}
I declared my services under Providers list in AppModule - haven't injected at component level
@NgModule({
providers: [CommonService, ModuleServiceA..]
...
})
export class AppModule {}
I couldn't inject directly in constructor as below which would then mandate all child services are also declared with all arguments. Which I wanted to avoid.
constructor(public cacheService: CacheService)
However, with above hierarchical architecture, as am calling super() constructor in every child Service, a new instance of BaseService/CommonService is created - defeating the base purpose.
Also, the Observable am creating in BaseService [listingObservable] is not unique anymore and my subscribers in components and other places are not being notified at all.
Please can someone advise how can I use hierarchical architecture but still have one instance of each service created!