作者:我就是人家 | 来源:互联网 | 2023-02-12 10:20
当一个可观察的对象运行时,它依赖于来自另一个可观察对象的数据,我无法弄清楚如何正确处理这种依赖关系。
一个可观察的对象从Firebase获取数据,并通过订阅它创建了一个简单的数字数组,称为NovelsRead:数组
另一个可观察到的对象从api获得响应,并且订阅它的目的是过滤出所有小说中存在id的记录。
问题是,当响应来自api时,NovelsRead []仍为空,因为Firebase尚未响应,因此从api响应中将不会过滤任何内容。
代码如下:
导出类首页{
currentnovels: any;
novels: any;
unreadnovels: any;
nextnovels: any;
novel: any;
resultsPageNumber: number = 1;
novelFullPosterPath: any;
novelsread: Array = [];
private basePosterUrlMedium = 'http://image.novels.org/t/p/w500';
private basePosterUrlSmall = 'http://image.novels.org/t/p/w185';
constructor(private http: Http,
private novelsApi: NovelsApiService,
private dataService: DataService,
) {
//this takes data from Firebase and pushes it to simple array of ids (numbers)
this.dataService.list('novels-read')
.subscribe(data => {
data.map(results => {
this.novelsread.push(results.novelsId);
})
})
}
ngAfterViewInit() {
this.novelsApi.getnovelsByPage(this.resultsPageNumber)
.subscribe(data => {
this.novels = data.results;
this.novels.map(data => {
data.full_poster_path = this.basePosterUrlMedium + data.poster_path;
return data;
})
.filter(data => {
let found = this.novelsread.indexOf(data.id);
//It seems when the api responds, this.novelsRead is still empty [] because Firebase has not responded yet
console.log("this novelsread[0] is ", this.novelsread[0]);
console.log("data.id found is ", found);
return data;
})
})
}
我正在寻找最干净的解决方案,无论是使用事件,可观察的链条还是任何其他建议,例如将函数从构造函数移至ngAfterViewInit,反之亦然。
我确实看过使用CombineLatest组合可观察对象的代码示例,但发现语法非常复杂,并且想知道是否有一种更干净的方法来实现我所需要的,即使这涉及等待事件。
1> mrkosima..:
使用forkJoin
应该可以帮助您。它仅在两个请求都完成时才允许处理结果:https :
//github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/forkjoin.md
或者,如果您的第二个请求取决于第一个响应-使用 switchMap
const request1$ = Rx.Observable.of('response1').delay(2000);
const request2$ = Rx.Observable.of('response2').delay(100);
Rx.Observable.forkJoin(request1$, request2$)
.subscribe(res => console.log(`forkJoin: ${res}`));
request1$.switchMap(res1 => {
console.log(`switchMap: ${res1}`);
return request2$;
}).subscribe(res2 => console.log(`switchMap: ${res2}`));