繁体   English   中英

Angular8:拦截http响应时出错

[英]Angular8: Error intercepting http response

我正在尝试使用角度拦截器拦截所有 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;      
      })
    );

但是打字稿给出了错误

ERROR in src/app/shared/interceptors/auth.interceptor.ts(35,17): error TS2540: Cannot assign to 'body' because it is a read-only property.

我应该怎么做才能解决这个问题?

注意:使用Object.assign克隆对象仍然会为新对象提供相同的错误。

你不能像这样重新分配变量:

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;      
  })
);

既然你已经重新分配了变量,你应该能够改变它的主体

编辑:如果你确定你的对象中有 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;
    );    

event对象的body属性是只读的,您不能重新定义/重新分配它。 您可以做的是将事件复制到新创建的事件中,修改此事件的主体,然后返回此对象。

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;      
      })
    );

最后用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM