HttpInterceptor基于来自其他observable的值更改响应体

时间:2017-12-05 15:17:58

标签: javascript angular typescript angular-http-interceptors

我似乎无法根据另一个observable的值更改响应体,我只能在检索到响应后才能获得该值。

更改请求非常简单,我不知道如何使用响应。

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

所以基本上我想要返回一个新的响应主体,上面有一个新属性'message'。

2 个答案:

答案 0 :(得分:1)

由于拦截返回和可观察,你可以将它切换到翻译服务的getEvent。像所以

@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.body.message=value)));

    });
  }
}

答案 1 :(得分:1)

由于您无法直接更改响应正文,因此必须返回克隆的响应正文。请参阅下面的最终答案。

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