I am running into a very strange situation with Angular Components and rxjs Subscriptions.
I have the following ngOnInit and ngOnDestroy functions
ngOnInit() {
zip(this.service.getMessage, this.service.getType)
.pipe(takeUntil(this.componentDestroyed$))
.subscribe(data => {
const notification = new Notification(data[0], data[1]);
this.notifications.push(notification);
});
}
ngOnDestroy(): void {
this.componentDestroyed$.next(true);
this.componentDestroyed$.complete();
}
The subscription is active after setting the values with a Source and Subject paradigm in a service file that looks like this:
private messageSource = new BehaviorSubject<string>('');
private message = this.messageSource.asObservable();
private typeSource = new BehaviorSubject<number>(-1);
private type = this.typeSource.asObservable();
...
...
set setMessage(message: string) {
this.messageSource.next(message);
}
set setType(type: number) {
this.typeSource.next(type);
}
The initial subscription works fine, as expected. However, navigating away from the Component and navigating back to the same Component runs the zip subscription again in ngOnInit, even after the component was destroyed when navigating away. How to prevent this from happening? I have also tried defining a subscription variable and calling unsubscribe. I am stumped.