Within my Angular service, I have a public Observable named usageDoc$
.
Here is the code snippet from the service file:
usageDoc$: Observable<IUsage>;
initializeUsageDoc() {
// This method is called in app.component.ts when the app loads
...
// Some asynchronous database querying
this.usageDoc$ = this.firestore.getUsageDoc(user.uid); // The getUsageDoc(..) method returns an Observable<IUsage>
}
This is how it is handled in the component file:
localDoc: any;
ngOnInit() {
this.service.usageDoc$.subscribe(doc=>this.localDoc=doc);
}
An error occurs stating:
cannot read property subscribe of undefined...
because usageDoc$
is not initialized during component initialization. As a workaround, I am currently creating a separate observable usageDocReady$ = new Subject<boolean>
in the service that emits as soon as usageDoc$
is set.
Is there a better way to resolve this issue? Is there a method to initialize usageDoc$
with a default value?
I understand that this issue wouldn't exist if I used the async pipe directly in the template, but I require a regular variable for display purposes, hence why I utilize localDoc
.