[英]Angular8: Error intercepting http response
I am trying to intercept all the HttpResponse using angular interceptor as我正在尝试使用角度拦截器拦截所有 HttpResponse 作为
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response and headers you want
event.body = event.body.data || event.body;
console.log('event--->>>', event);
}
return event;
})
);
but typescript gives an error但是打字稿给出了错误
ERROR in src/app/shared/interceptors/auth.interceptor.ts(35,17): error TS2540: Cannot assign to 'body' because it is a read-only property.
What should I do to tackle this?我应该怎么做才能解决这个问题?
NOTE: Cloning the object using
Object.assign
still gives the same error for new object.注意:使用Object.assign
克隆对象仍然会为新对象提供相同的错误。
can't you reassign the variable like this :你不能像这样重新分配变量:
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
let returnValue = Object.assign({}, event);
if (event instanceof HttpResponse) {
// do stuff with response and headers you want
returnValue.body = event.body.data || event.body;
console.log('event--->>>', event);
}
return returnValue;
})
);
since you've reassigned the variable, you should be able to change it's body既然你已经重新分配了变量,你应该能够改变它的主体
EDIT : if you are sure you have the body property inside your object you can do the assignation like this编辑:如果你确定你的对象中有 body 属性,你可以像这样进行分配
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
let returnValue = Object.assign({}, event);
if (event instanceof HttpResponse) {
// do stuff with response and headers you want
returnValue.body = event['body'].data || event['body'];
console.log('event--->>>', event);
}
return returnValue;
);
The body
property of the event
object is readonly, You cannot redefine / reassign it. event
对象的body
属性是只读的,您不能重新定义/重新分配它。 What you could do, is copy the event into a newly created event modify the body of this event and then return this object.您可以做的是将事件复制到新创建的事件中,修改此事件的主体,然后返回此对象。
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// we use this syntax to deep copy the event.
// we don't want any reference to the previous event.
const newEvent = {...event};
// we edit the copied event.
newEvent.body = newEvent .body.data || newEvent .body;
console.log('event--->>>', newEvent );
// we need to return the new event.
return newEvent
}
// nothing is happening, we are returning the event.
return event;
})
);
Finally solved it using the event.clone method最后用event.clone方法解决了
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
let newEvent: HttpEvent<any>;
// alter response here. maybe do the following
newEvent = event.clone({
// alter event params here
body: event.body.data || event.body
});
return newEvent;
}
})
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.