HttpInterceptor change response body based on value from other observable

杀马特。学长 韩版系。学妹 提交于 2020-01-14 03:39:08

问题


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.


回答1:


Since the intercept returns and observable you can switchMap it to the translate service's getEvent. Like So

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

    });
  }
}



回答2:


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


来源:https://stackoverflow.com/questions/47656992/httpinterceptor-change-response-body-based-on-value-from-other-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!