Search code examples
angularhttpclientangular-http-interceptors

How to fetch a header value/ body json value from HttpClient interceptor


My Angular version: 6.0.3 and using HttpClient module

Hello in below code I am trying to fetch res.headers and res.body to fetch for example: res.headers.status, res.body.id if possible:

but whenever I try to log in the console. it generates errors. using syntax res['headers'], res['body'] can be printed in the console. but no further fetching possible.

HttpsInterceptor Class:

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs";
import { tap, finalize } from "rxjs/operators";
//import { MessageService } from '../../message.service';

export class HttpsInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler):
        Observable<HttpEvent<any>> {       

        const started = Date.now();
        let ok: string;        
        let res: any;

        console.log(req.headers.keys());
        // return next.handle(req);

        // clone request and replace 'http://' with 'https://' at the same time
        const secureReq = req.clone({
            url: req.url.replace('http://', 'https://')
        });
        // send the cloned, "secure" request to the next handler.
        return next.handle(secureReq).pipe(            
            tap(
                // Succeeds when there is a response; ignore other events
                (event) => { 
                    ok = event instanceof HttpResponse ? 'succeeded' : ''
                    res = event;
                    console.log("Response:", res);
/* NOT WORKING */                        console.log("res: headers", res.headers);
/* NOT WORKING */                        console.log("res: body", res.body); 
                },
                // Operation failed; error is an HttpErrorResponse
                error => ok = 'failed'),
            finalize(() => {
                const elapsed = Date.now() - started;
                const msg = `${req.method} "${req.urlWithParams}"
                   ${ok} in ${elapsed} ms.`;
                //this.messenger.add(msg);
                console.log(msg);
            })
        );
    }
}

Console log:

Response: 
{…}
​
body: {…}
​​
address: "76, Shilpgram tenaments, Soma talav, Dabhoi ring road, Vadodara, Gujarati, India - 390001"
​​
email: "cust@ngapp.com"
​​
fullname: "Amit Shah"
​​
id: 1
​​
password: "cust1234"
​​
phone: "+91-123456789"
​​
<prototype>: Object { … }
​
headers: {…}
​​
lazyInit: function lazyInit()
​​
lazyUpdate: null
​​
normalizedNames: Map(0)
​​
<prototype>: Object { has: has()
, get: get(), keys: keys()
, … }
​
ok: true
​
status: 200
​
statusText: "OK"
​
type: 4
​
url: "https://demo1601932.mockable.io/customer/get/1"
​
<prototype>: Object { constructor: HttpResponse()
, clone: clone() }

Solution

  • Actually, next.handle(...) returns Observable<HttpEvent>.

    This HttpEvent is 5 types.

    type HttpEvent<T> = HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>;

    So, you've to read response header when it is the type of HttpResponse. I just added a if block in your code.

    return next.handle(secureReq)
        .pipe(            
                tap((event) => { 
                       ok = event instanceof HttpResponse ? 'succeeded' : '';
                       if(ok) {
                         res = event;
                         console.log("Response:", res);
                         console.log("res: headers", res.headers);
                         console.log("res: body", res.body);
                       }
                 })
    
            );