gpt4 book ai didi

javascript - 如何避免第一个未定义的订阅 JavaScript RxJS

转载 作者:行者123 更新时间:2023-11-30 08:24:08 25 4
gpt4 key购买 nike

我想订阅从服务器获取的一些对象。但是第一次的代码没有给我任何返回。订阅的代码:

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
});
}

服务看起来像这样,我正在为 Observable 使用 BehaviorSubject:

 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();
}

如何避免此错误并只订阅已定义的事件

最佳答案

我只想添加一个过滤器来排除初始订阅中的未定义事件:

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
});
}

关于javascript - 如何避免第一个未定义的订阅 JavaScript RxJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48411012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com