Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

javascript - Angular 4.3 HttpClient : Intercept response

In the documentation about the new HttpClientModule included in the new version of Angular 4.3, the mechanism to intercept requests is explained very well. There is also mention of the response interceptor mechanism however I cannot find anything about it.

Does anyone have an idea about how to intercept a response in order to modify the body message before it is sent to the service?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recently made an HttpInterceptor in order to resolve cyclical references in some JSON on the client side, essentially replacing any object with a $ref property with the object in the JSON that has a matching $id property. (This is the output you get if Json.Net is configured with PreserveReferencesHandling.Objects and ReferenceLoopHandling.Ignore).

The answers here helped me some of way, but none of them show how to modify the body of the response, like the OP needs. In order to do so, one needs to clone the event and update the body, like so:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).map(event => {
        if (event instanceof HttpResponse && shouldBeIntercepted(event)) {
            event = event.clone({ body: resolveReferences(event.body) })
        }         
        return event;
    });
}

Any event that should not be modified is simply passed through to the next handler.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...