Reputation: 924
I want to subscribe some object that I get from server. But code for first time return me nothing. Code that is subscribe:
ngOnInit() {
this.dataService.getEvents()
.subscribe(
(events) => {
this.events = events;
console.log(events); // when I try to get this is no problem it prints log to console (probably because event is var so it is not defined)
console.log(events[0].name); // it didn't see that property so I'm getting ERROR TypeError: Cannot read property 'name' of undefined
});
}
Service looks like this, I'm using BehaviorSubject
for Observable:
private eventChanged = new BehaviorSubject<any>([]);
constructor(private http: HttpClient) {
this.refetch();
}
private refetch(): void {
this.http.get<EventE[]>(this.baseUrl)
.subscribe(events => {
this.events = events;
this.eventChanged.next(events);
});
}
getEvents(): Observable<any> {
return this.eventChanged.asObservable();
}
How to avoid this error and only subscribe event that is Defined
Upvotes: 1
Views: 1432
Reputation: 82614
I would just add a filter to exclude undefined events on the initial subscription:
ngOnInit() {
this.dataService.getEvents()
.filter(events => events && events.length > 0)
.subscribe(
(events) => {
this.events = events;
console.log(events); // when I try to get this is no problem it prints log to console (probably because event is var so it is not defined)
console.log(events[0].name); // it didn't see that property so I'm getting ERROR TypeError: Cannot read property 'name' of undefined
});
}
Upvotes: 5
Reputation: 1913
Instead of using a BehaviorSubject you can try using a Subject, the Subject won't have the empty array in the first place which triggers the initial subscription call.
If you need to use a BehaviorSubject, you can instead do a check for null and has length before working with it, so
.subscribe(events => {
if(events && events instanceof Array && events.length > 0){
this.events = events;
this.eventChanged.next(events);
}
});
Upvotes: 2