问题
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