I have used behavior subject to next an observable.
component1.ts
this._service.searchText(result);
service.ts
private searchSubject= new Subject<any>();
searchText(mission: any) {
this.searchSubject.next(mission);
}
search$ = this.searchSubject.asObservable();
component2.ts
subscriptions: Array<Subscription> = [];
constructor(private _service: service,) {
tempSubscription = _service.search$.subscribe(
(mission: any) => {
console.log("subscribed to search");
if (mission) {
//Code
}
});
this.subscriptions.push(tempSubscription)
tempSubscription = _service.someOtherObservable$((event)=>{
//Code.
});
this.subscriptions.push(tempSubscription)
}
ngOnDestroy(): void {
for (let sub of this.subscriptions) {
sub.unsubscribe();
}
}
If I remove subscription.push(tempSubscription)
after subscribing to $search then subscription work. Else nothing logs within it. Also If I take different variables for both storing output of both observable then also it works.
Note: Same observable is subscribed in other components in a similar way and it is working fine. What am I doing wrong by pushing observables into an array and then unsubscribing?