Within my Angular 8 project, I have a component that is dependent on a service for data loading. It waits for a notification from the service signaling that it has finished loading in the following manner:
constructor(public contentService: ContractService) {
let self = this;
let sub = contentService.loaded.subscribe(function(loaded) {
if (loaded) {
self.loading = false;
if (sub) {
sub.unsubscribe();
}
}
});
}
This setup functions correctly most of the time, but occasionally an error message surfaces:
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)
The abstract-content-component
mentioned in the error is actually a parent class with multiple implementations, being called by a child class which serves as a shell without much logic to allow for easy template switching.
The error itself seems puzzling (particularly line 51 referring to the if(sub)
check), as how can a subscription not exist within its own event handler? This pattern has been successfully implemented elsewhere in my codebase, so why does this specific instance encounter issues?