在 $http 调用期间,我在我的 Angular (4.0) 应用程序中使用了以下代码。
return this.httpComponent.post(serviceUrl, request, args)
.map((res: any) => res.json() as R)
.catch((error: any) => Observable.throw(error.json().error || error.json().errorMessage || 'Server error'));
测试后,我意识到多个订阅会多次触发请求。感谢这篇文章:Angular2 http.post gets executed twice我发现我需要share()结果。
这可以消除多次调用,但现在看来我的 catch() 方法没有被触发。我希望我的 catch() throw 错误。
我尝试了下面的两个选项,但它们没有用:
return this.httpComponent.post(serviceUrl, request, args)
.map((res: any) => res.json() as R)
.share()
.catch((error: any) => Observable.throw(error.json().error || error.json().errorMessage || 'Server error'));
return this.httpComponent.post(serviceUrl, request, args)
.map((res: any) => res.json() as R)
.catch((error: any) => Observable.throw(error.json().error || error.json().errorMessage || 'Server error')
.share()); //This doesn't make sense since my catch() isn't returning an Observable
有谁知道我怎样才能同时share() 和catch(throw...)?
最佳答案
正如我在对@cartant 的回答的评论中提到的,如果任何订阅者没有错误处理程序(即:不关心任何错误场景),则会抛出异常并且所有后续订阅者都不会被告知原始错误。
在我看来,这似乎是一个设计缺陷。这是示例(从@cartant 的回答中复制)
const source = Rx.Observable
.interval(500)
.map((value) => {
if (value === 2) {
throw new Error("Boom!");
}
console.log(`value: ${value}`)
return value;
})
.catch((error) => Rx.Observable.throw(new Error(`Re-thrown ${error.message}`)))
.share();
source.subscribe(
(value) => console.log(`subscription 1: ${value}`)
);
source.subscribe(
(value) => console.log(`subscription 2: ${value}`),
(error) => console.log(`subscription 2: ${error}`)
);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>
关于angular - RxJS 将 catch() 添加到已共享的 Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45178011/