[我在ngOnInit中实现了对两个api路由的调用,以获取一些数据,我使用的是angular 7,并实现forkJoin来像这样调用api:
ngOnInit() {
debugger
this.route.params.pipe(
switchMap(params => forkJoin([
this.http.get('/api/surveys/' + params.id),
this.http.get('/api/surveys/getStatistics/' + params.id)
]))
).subscribe(result => {
this.survey = result[0];
this.statistics = result[1];
this.updateChart(result[1]);
},
error => this.handleError(error)
);
}
private handleError(error) {
debugger
if (error.status === 400) {
this.showError(error.error.error, 'Erreur!');
if (error.error.error === 'Le sondage demandé n\'existe plus!') {
this.router.navigateByUrl('/sondage');
}
}
}
private updateChart(statistics) {
debugger
statistics.options.forEach(option => {
this.pieData.push(option.number);
option.color = this.d3Colors[this.colorCounter];
this.colorCounter = this.colorCounter + 1;
});
}
在第一个调试器之后,代码不会运行对API的调用请求,而是直接传递给handleError函数!并生成500个服务器错误
500通常是API服务器本身抛出的错误。如果您的设计允许,则应将两个API调用分开。这是第一次通话失败不会影响第二次通话。
来自forkJoin规范:“如果在某个时候任何输入可观察到的错误,forkJoin也会发生错误,所有其他可观察到的将立即取消订阅。”
因此,一个调用的失败使其他API调用成功变得无关紧要,因为已经取消订阅。