In my Angular 8 application I have a component that subscribes to a service and awaits a notification that the service has loaded like this:
constructor(public contentService: ContractService) {
let self = this;
let sub = contentService.loaded.subscribe(function(loaded) {
if (loaded) {
self.loading = false;
if (sub) {
sub.unsubscribe();
}
}
});
}
This works correctly in most cases but sometimes I am seeing the following error message:
ERROR ReferenceError: Cannot access 'sub' before initialization
at SafeSubscriber._next (abstract-content.component.ts:51)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:185)
at SafeSubscriber.next (Subscriber.js:124)
at Subscriber._next (Subscriber.js:72)
at Subscriber.next (Subscriber.js:49)
at BehaviorSubject._subscribe (BehaviorSubject.js:14)
at BehaviorSubject._trySubscribe (Observable.js:42)
at BehaviorSubject._trySubscribe (Subject.js:81)
at BehaviorSubject.subscribe (Observable.js:28)
at Observable._subscribe (Observable.js:76)
As you might gather from the name the abstract-content-component is a parent class that has several implementations so this is called from a child class, but that is effectively an empty shell with no logic of its own that I am using to make it easy to switch templates.
The error message seems nonsensical to me ( line 51 in this case is the if(sub) check which I added because I was seeing the same error in the line after ) because how can the subscription not exist if we are inside its own event handler? I use this pattern in other places successfully, why is there a problem here?