rxjs中多个调用的角度句柄错误



在这种特殊情况下,我不知道用rxjs处理html错误的最佳方法:

组件.ts

private open() {
this.openSubscription = this.openService
.open(this.id)
.subscribe(res => {
if (res) {
// do something with result
} else {
this.openInError = true;
}
});
}

open.service.ts

open(id: number): Observable<OpenContext> {
const openContextObservable = new Observable<OpenContext>(
observer => {
this.openApiService
.first(id)
.pipe(
catchError(err => of(err))
)
.subscribe(res => {
this.openApiService
.second(res.param1)
.pipe(
map(result=> {
// do something with the result
observer.next(openContext);
observer.complete();
}),
catchError(err => of(err))
)
})
})}

在服务api中,我只返回了这个.http.post(…(,并带有一些参数作为Observable

我想先捕获错误,然后在组件的订阅中处理它(subscribe(res=>…,err=>…((。事实上,如果"first"出现错误,它会调用"second",即使它需要"first("的结果,之后它不会返回错误,只是如果订阅中没有响应,我会处理。

执行该操作并拥有干净代码的最佳方式是什么?我测试了throwError。。。但我被阻止了。。。

因此组件中预期的代码是:

private open() {
this.openSubscription = this.openService
.open(this.id)
.subscribe(
res => {
if (res) {
// do something with result
}
},
err => {
if (err) {
this.openInError = true;
}
});
}

或者类似于.pipe和map的东西。

1。(删除catchErrors,因为这将捕获错误并将错误流转换为非错误流。

2.(使用switchMap而不是嵌套订阅。

open.service.ts

import { switchMap } from 'rxjs/operators';
....
open(id: number): Observable<OpenContext> {
// you can get rid of openContextObservable as well.
return this.openApiService
.first(id)
.pipe(
// switch to this observable from the first one
switchMap(res => this.openApiService.second(res.param1)),
map(result => {
// do stuff and transformations here but make sure you return result for your subscriber.
return result;
})
);
)}

组件

private open() {
this.openSubscription = this.openService
.open(this.id)
.subscribe(
res => {
if (res) {
// do something with result
}
},
err => {
if (err) {
this.openInError = true;
}
});
}

最新更新