【问题标题】:How to fetch a header value/ body json value from HttpClient interceptor如何从 HttpClient 拦截器中获取标头值/正文 json 值
【发布时间】:2018-12-02 21:50:55
【问题描述】:

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

【问题讨论】:

标签: angular httpclient angular-http-interceptors


【解决方案1】:

实际上,next.handle(...) 返回Observable&lt;HttpEvent&gt;

这个HttpEvent有5种类型。

type HttpEvent&lt;T&gt; = HttpSentEvent | HttpHeaderResponse | HttpResponse&lt;T&gt; | HttpProgressEvent | HttpUserEvent&lt;T&gt;;

所以,当它是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);
                   }
             })

        );

【讨论】:

  • 准确答案,谢谢。你能告诉更多关于res.headers.customHeader 的信息吗?如果您的答案是 CORS 设置,那么我知道:P
猜你喜欢
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 2020-12-09
相关资源
最近更新 更多