我有2个服务budgetTestService
和budgetService
,出现错误时需要使用budgetTestService,而没有错误时则需要使用budgetService。 budgetTestService.getBudgetService()
管道中的map()未被调用-console.log('test service complete');
不确定这是怎么做的,好像是在嵌套并且做错了,我使用的语法正确吗?
this.budgetService.getBudgetDays(this.startDate, this.finishDate)
.pipe(
map(res => {
console.log('get budget day server mapping');
self.timelineBudgetDates = self.processDates(res);
}),
//map(res => {
// self.timelineBudgetDates = self.budgetTestService.getBudgetDates(self.startDate, self.finishDate);
//})
catchError(error => {
console.log('error code running');
console.log(error);
self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
.pipe(
map(res => {
console.log('test service complete');
console.log(res);
self.timelineBudgetDates = res;
})
);
return of('some return value, maybe null, maybe a good default');
})
)
.subscribe(res => {
console.log('Response = ', res);
//self.timelineBudgetDates = self.processDates(res);
//self.timelineBudgetDates = res;
});
budgetTestService
:
getBudgetDates(startDate: string, endDate: string): Observable<BudgetDate[]> {
console.log('getting budget dates from test service');
let dates = this.datesOfRange(moment(startDate), moment(endDate));
//console.log('dates:', dates);
let budgetDates: BudgetDate[] = [
new BudgetDate({ moment: moment().subtract(1, 'd').startOf('d'), earned: 100, spent: 50, onServer: true }),
new BudgetDate({ moment: moment().subtract(2, 'd').startOf('d'), earned: 101, spent: 51, onServer: true }),
new BudgetDate({ moment: moment().subtract(3, 'd').startOf('d'), earned: 102, spent: 52, onServer: true }),
new BudgetDate({ moment: moment().subtract(4, 'd').startOf('d'), earned: 103, spent: 53, onServer: true })
];
const mockResults = function(observer: Observer<BudgetDate[]>) {
observer.next(budgetDates);
observer.error('...');
observer.complete;
};
const update = new Observable(mockResults).pipe(
catchError((error: any) => Observable.throw(error))
);
return update;
}
输出:
不包括:test service complete
error code running
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
getting budget dates from test service
Response = some return value, maybe null, maybe a good default
答案 0 :(得分:1)
RxJS可观察链仅在订阅时才执行。因此,输出中不包含test service complete
的问题是您从不订阅测试服务调用。特别的问题在这里:
catchError(error => {
self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
.pipe(
// ...
);
// RETURNING OTHER OBSERVABLE HERE
return of('some return value, maybe null, maybe a good default');
})
// ...
.subscribe(console.log)
您在这里调用budgetTestService
,但从未订阅其Observable。
比较一下:
catchError(error => {
return self.budgetTestService.getBudgetDates(self.startDate, self.finishDate)
.pipe(
// ...
);
})
// ...
.subscribe(console.log)
在后面的代码示例中,我们从budgetTestService
返回observable,它将成为订阅链的一部分。
在这里检查这个小例子进行比较:"async error handler in RxJS"
希望这会有所帮助