Reputation: 15
I'm facing this problem where when I call the following method to subscribe upon page refresh, the error "Cannot read property 'subscribe' of undefined" occurs
Here are my imports:
import {Observable} from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import "rxjs/add/operator/mergeMap";
Here's my method which is causing the error when I refresh the page:
getChildSubItem(subItemTag:string): Observable<ChildSubItem[]> {
return this.subItemObservers$.mergeMap(obs => {
return obs.find(s => s.subItemTag === subItemTag)
.viewSubItemSource.asObservable();
});
}
I have few properties which is used to create the BehaviorSubject and the Observable for the BehaviorSubject. I created an observable for the array of SubItemObservers as I need it to be populated first through another service call.
private subItemObserversSource = new BehaviorSubject<SubItemObservers[]>([]);
private subItemObservers$: Observable<SubItemObservers[]> = new Observable<SubItemObservers[]>();
Here's the class for SubItemObservers:
export class SubItemObservers {
subItemTag: string;
viewSubItemSource: BehaviorSubject<ChildSubItem[]> = new BehaviorSubject<ChildSubItem[]>([]);;
}
Based on Google search, I need to complete the method to return Observable object. But, I'm not sure how to do that with my solution. Can someone help me on how should I completed the subscription in the method in order to resolve the error. What am I missing? Thank you.
Upvotes: 0
Views: 813
Reputation: 513
First of all, BehaviourSubject inherits Observable, so probably you don't need 2 streams like that.
Secondly, rxjs6 has a best practice of using pipe
.
Within getChildSubItem, you can just call this.subItemObserversSource.pipe(mergeMap...)
.
As soon as you initialise your subItemObserversSource = new BehaviourSubject
in declaration, you shouldn't get any undefined error.
Also, it would always be nice to double check obs.find(s => s.subItemTag === subItemTag)
in case it returns undefined
.
Hope it helps.
Upvotes: 1