是否可以避免在以下代码中嵌套订阅?
this.requestService().subscribe(
() => this.success(),
error => {
const errorDescription = {
one: 5,
two: 10
};
return this.error(errorDescription).subscribe();
}
);
第二个subscribe
是Observer错误回调的一部分。我们怎么能使用例如switchMap
只有一个订阅?
好像你需要一个catchError
,它可以让你用另一个流替换错误。虽然我们必须更新成功的结果处理:
this.requestService().pipe(
// handle success value
tap(() => this.success()),
// when an error happens
catchError(error => {
const errorDescription = {
one: 5,
two: 10
};
// we switch to `this.error` stream
return this.error(errorDescription);
})
).subscribe(value=>{
// ...here you'll receive both:
// events from the requestService()
// and events from this.error(errorDescription)
});
下面是一篇详细介绍error handling in RxJS的文章
希望这可以帮助
这是一个避免'嵌套'订阅的想法。使用您提供的代码,这是我能想到的最好的代码。如果您有任何疑问,请告诉我,我会帮忙。
import { of, throwError } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';
// this.requestService().subscribe(
// () => this.success(),
// error => {
// const errorDescription = {
// one: 5,
// two: 10
// };
// return this.error(errorDescription).subscribe();
// }
// );
const error = throwError('oops');
const success = of('success!');
const handleError = (d) => of({one: 5, two: 10}).pipe(
map(n => n),
catchError(e => 'could not do 2nd network request')
);
const requestServiceSuccess = success.pipe(
switchMap(d => of(d)),
catchError(handleError)
)
const requestServiceFail = error.pipe(
switchMap(d => of(d)),
catchError(handleError)
)
// if your first network request succeeds, then you will see success
requestServiceSuccess.subscribe(
(d) => console.log(d),
(e) => console.log(e)
)
// if your first network request fails, then you will see your errorDescription
requestServiceFail.subscribe(
(d) => console.log(d),
(e) => console.log(e)
)
您可以将其粘贴到stackblitz中以检查日志
我可能会这样做:
this.requestService().pipe(catchError(e => {
const errorDescription = {
one: 5,
two: 10
};
return this.error(errorDescription).pipe(switchMap(empty()));
// the switch to empty will prevent the error going to success
// consider moving this into the error handler itself.
})).subscribe(
() => this.success(),
error => {
//should never get here.
}
);
catchError - > switchMap - > empty是一种在我的代码中经常出现的模式,因为我的错误处理程序应该经常停止处理链。