如何从HttpClient拦截器获取标头值/正文json值

时间:2018-06-23 19:44:53

标签: angular httpclient angular-http-interceptors

  

我的Angular版本: 6.0.3 并使用 HttpClient 模块

您好,我在下面的代码中尝试获取res.headersres.body以获取例如: res.headers.status,如果可能,请res.body.id

,但是每当我尝试登录控制台时。它产生错误。 使用语法res['headers'],可以在控制台中打印res['body']。但无法进一步获取。

HttpsInterceptor类:

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

控制台日志:

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

1 个答案:

答案 0 :(得分:1)

实际上,next.handle(...)返回Observable<HttpEvent>

HttpEvent有5种类型。

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

因此,当它是HttpResponse类型时,您必须读取响应头。我刚刚在您的代码中添加了if块。

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

        );