这是我正在使用的代码,即使导入了getBudgetDays
也没有flatMap / mergeMap。
import { mergeMap, tap, map } from 'rxjs/operators';
import { Observable } from 'rxjs';
出现错误时,我需要订阅另一项服务budgetTestService
。我正在尝试使用flatMap
来避免嵌套,但不确定如何使用它。
this.budgetService.getBudgetDays(this.startDate, this.finishDate)
.subscribe({
next(budgetDates) {
},
error(error) {
// not sure but I don't think rxjs should have nested callbacks like this.
self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
.subscribe({
next(budgetDates) {
},
error(error) {}
});
}
});
答案 0 :(得分:1)
干净的语法是
this.budgetService.getBudgetDays(this.startDate, this.finishDate).pipe(
catchError(res => this.budgetTestService.getBudgetDates(this.startDate, this.finishDate)),
).subscribe(res => {
// res = value of getBudgetDays if no error, or getBudgetDates if there is one
});
您正在使用旧的,不推荐使用的语法。现在,这一切都通过管道运算符完成!