rxjs/ajax 响应 无法将对象'[object Object]'的只读属性'taskData'分配给只读属性



在一个有角度的应用程序中,我创建了一个服务,通过GET从后端获取json对象。

当我使用这个fetch代码块时,一切都很好:

fetchNode(nodePath: string): Promise<CrxApiNode> {
const {token} = this.authInfo$;
return fetch(`${nodesUrl}?path=${encodeURIComponent(nodePath)}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'application/json; charset=utf-8'
}
}
).then(res => {
return res.json();
}).catch(e => {
console.log('error');
});

}

使用rxjs/ajax:执行相同请求时

loadNode(nodePath: string): Observable<CrxApiNode> {
const {token} = this.authInfo$;
// this leads to the error
return ajax.getJSON(`${nodesUrl}?path=${encodeURIComponent(nodePath)}`, {
Authorization: `Bearer ${token}`,
Accept: 'application/json; charset=utf-8'
}).pipe(
map(node => {
return node;
}),
catchError(error => {
// here the error occurs: Cannot assign to read only property 'taskData' of object '[object Object]'
console.log('error: ', error);
return of(error);
}));

}

我得到错误(由ajax抛出(…(:

"TypeError: Cannot assign to read only property 'taskData' of object '[object Object]'
at XMLHttpRequest.addEventListener (http://localhost:4200/polyfills.js:1939:39)
at XMLHttpRequest.desc.set [as ontimeout] (http://localhost:4200/polyfills.js:1292:24)
at AjaxSubscriber.setupEvents (http://localhost:4200/vendor.js:78731:23)
at AjaxSubscriber.send (http://localhost:4200/vendor.js:78652:18)
at new AjaxSubscriber (http://localhost:4200/vendor.js:78634:14)
at AjaxObservable._subscribe (http://localhost:4200/vendor.js:78605:16)
at AjaxObservable._trySubscribe (http://localhost:4200/vendor.js:77010:25)
at AjaxObservable.subscribe (http://localhost:4200/vendor.js:76996:22)
at MapOperator.call (http://localhost:4200/vendor.js:82439:23)
at Observable.subscribe (http://localhost:4200/vendor.js:76991:31)"
enter code here

由于我对rxjs还很陌生,我正在努力分析错误——这里有什么区别,为什么rxjs变体没有按预期工作?

在第一个例子中,您捕获错误并将其记录下来。因此,错误现在"消失"了。

在第二个示例中,您还捕获了错误,并将其记录下来,但随后错误发生了。"catchError"将从流中捕获一个错误,并将一个新的VALUE(而不是错误(返回到流中。原因是,您现在可以捕捉错误并将其替换为默认值,以便为用户尽可能平滑地处理错误。

因此,流现在会发出一个错误Object。没有将其作为错误处理。我假设稍后您将调用"myEmitedValue.taskData"。但是"myEmited Value"不是来自后端调用的JSON,而是错误对象。因此没有"taskData"。

如果你想"重新思考"错误,你可以改为

return throwError(err)

我用几个例子创建了一个stackblitz。

相关内容

最新更新