Angular 5组合或重构多个订阅调用
我正在我的web项目中使用Angular 5.2。在其中一个页面中,我对不同的webAPI方法使用了多个subscribe调用。虽然它们是不同的,但独立的调用也带来了不同的数据集 但是我在想,有没有一种方法可以用一种语法将Subscribe调用组合在一起,使代码看起来小巧整洁Angular 5组合或重构多个订阅调用,angular,rxjs,angular5,Angular,Rxjs,Angular5,我正在我的web项目中使用Angular 5.2。在其中一个页面中,我对不同的webAPI方法使用了多个subscribe调用。虽然它们是不同的,但独立的调用也带来了不同的数据集 但是我在想,有没有一种方法可以用一种语法将Subscribe调用组合在一起,使代码看起来小巧整洁 ngOnInit(): void { this._documentService.getTypes() .subscribe(px => { this._docTyp
ngOnInit(): void {
this._documentService.getTypes()
.subscribe(px => {
this._docTypeList = px;
},
error => {
console.log("Grid Err:: " + error.message);
}
);
this._documentService.getCategories()
.subscribe(rx => {
this._catList = rx;
},
error => {
console.log("Grid Err:: " + error.message); }
);
}
有没有办法重构这段代码使其简短
请建议 使用
forkJoin
组合多个观察值
forkJoin(this._documentService.getTypes(), this._documentService.getCategories() )
.subscribe(rx => {
this._docTypeList = rx[0]
this._catList = rx[1];
},
error => {
console.log("Grid Err:: " + error.message); }
);
让我快速尝试一下。forkJoin会同时进行多个API调用吗?是的。它将一次发送多个调用,并在订阅Nice Sachila:-)之前等待所有响应。比方说,如果我必须单独进行错误处理的话。我们可以使用这种语法吗?当它们加入时会发生什么?例如,如果一个有错误,那么另一个会发生什么?