我的问题与此How to throw error from RxJS map operator (angular)相似,但是我在使用rxjs6的angular6,我想一切都变了;)
我想知道,如何在可观察对象的映射内将Error-Object传播到订阅的OnError部分。我总是以OnNext部分结束。
这是我到目前为止所拥有的:
在ng-component内,我可能有以下方法调用
[...]
this.dataStreamService.execCall({ method : 'order_list',params : {}})
.subscribe( r => {
// here r provides the result data from http call
console.log("execCall result", r);
}, err => {
// HERE the "MAP ERROR OCCURED" Error should be occured as well,
// but in doesn't
console.log("execCall error",err);
});
[...]
被调用的服务方法如下:
execCall(dataStreamCall: DataStreamCall): Observable<DataStreamResult> {
let apiURL = '<some API-URL>';
let params = dataStreamCall.params;
// do HTTP request (this.http calls an extra service handler which wraps
// the angular httpClient and the API errors there
// There is NO Problem with that part :)
let apiResult = this.http.post(apiURL, params);
// Build a new Observable from type "DataStreamResult"
let dsr : Observable<DataStreamResult> = apiResult
.pipe(
map( httpresult => {
if (httpresult['status'] == false){
// the http call was basically successful,
// but state in data is false
// *** THIS IS NOT PROPAGATE TO SUBSCRIBE OnERROR ***
throwError({'msg' : 'MAP ERROR OCCURED'});
// also tried as alternative
return throwError({'msg' : 'MAP ERROR OCCURED'});
} else {
// here the http call was successful
let d = new DataStreamResult();
d.result = httpresult;
return d;
}
}),
catchError( err => {
// error is bubble up from http request handler
return throwError(err);
})
);
return dsr;
}
最后一个问题: 如何管理管道“ map”中的“ throwError”传播到订阅“ err => {...}”。
以下情况的实际行为:
throwError({..})
我最终以r = undefined
如果我使用:
return throwError({..})
我还结束了订阅的OnNext部分,其中r
是throwError-Observable
预先感谢 最好的问候
答案 0 :(得分:1)
throwError({'msg' : 'MAP ERROR OCCURED'})
将返回一个可观察到的内容,该内容在订阅时将产生error
通知。也就是说,它将调用订户的error
方法。
在摘要中,您调用throwError
并忽略该值。或者,您可以从传递给map
运算符的项目函数中返回其返回值。
都不会产生错误。
在第一种情况下没有订户,因为返回值被忽略。而且,在第二种情况下,没有订阅者,因为map
运算符不订阅它从项目函数接收的内容– map
运算符的项目函数可以返回任何内容;它不必返回一个可观察值。
要在map
中引发错误,请使用:
throw {'msg' : 'MAP ERROR OCCURED'};