HttpInterceptor 根据其他 observable 的值更改响应主体

问题描述:

有些我似乎无法根据另一个 observable 的值更改响应正文,我只能在检索响应后才能获得该值.

Some how i can't seem to change the response body based on the value from another observable which i can only get after i retrieved the response.

更改请求非常简单,我不知道如何处理响应.

Changing the request is pretty simple, i don't know how to do it with the response.

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).map((event: HttpEvent<any>) => {
      if (!(event instanceof HttpResponse)) return event;             

      const translateService = this._injector.get(TranslateService);

      // retrieved the key from the reponse, now need to retrieve data from the translateservice   
      translateService.get(`${event.body.key}`).subscribe((value: string) => {
        event.body.message = value;
      });

       // how to return new response ??  
      return event.clone({ body: event.body });  
    });
  }
}

所以基本上我想返回一个带有新属性消息"的新响应正文.

so basically i want to return a new reponse body with a new property 'message' on it.

由于您无法直接更改响应主体,因此必须返回一个克隆的响应主体.最终答案见下文.

Since you cant directly alter the response body you have to return a cloned one. See below for the final answer.

@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
  constructor(private _injector: Injector) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const translateService = this._injector.get(TranslateService);

    return next.handle(request)
        // filter out only events that HTTP event.
        .filter((event: HttpEvent<any>) =>(event instanceof HttpResponse))
        //then switch the observable to get the response of the translate service.
        .switchMap(event => translateService.get(`${event.body.key}`)
            .map(value => event.clone({ body: { message:value } }));
    });
  }
}