我有下面的代码,我一个接一个地调用 api,但另一个 api 调用发生在订阅内部。在这种情况下我们可以使用合并映射来避免多次订阅吗?
下面是我的代码
saveEmployees(empObject: any) {
from(
this.empService.saveEmployees(empObject)
).subscribe(
(res) => {
try {
this.getOfficeInfo();
this.stopLoading(false);
}
catch (error) {
this.setLoadingFlags(false);
this.toastr.error("Error Saving Employees...");
}
}
)
}
getOfficeInfo() {
this.empService.getOfficeInfo().subscribe(
(res: any) => {
if (res != null) {
this.RowData = res.data;
} else {
//
}
},
(err) => {
var test = "err";
}
);
}
尝试将上面的代码重构为下面的代码,出现错误
Promise any[] 类型上不存在属性管道并且 void 类型不可分配给 ObservableInput 类型
this.empService
.saveEmployees(empObject)
.pipe(
mergeMap((res: any) => {
return this.getOfficeInfo()
})
).subscribe((res: any) => {
//get office info here and assign to grid
});
由于我们不需要第一个可观察的数据,因此我们可以使用 switchMap
saveEmployees(empObject: any) {
from(this.empService.saveEmployees(empObject))
.pipe(switchMap(() => this.empService.getOfficeInfo()))
.subscribe({
next: (res: any) => {
this.stopLoading(false);
if (res != null) {
this.RowData = res.data;
} else {
//
}
},
error: (err) => {
this.setLoadingFlags(false);
var test = 'err';
this.toastr.error('Error Saving Employees...');
},
});
}