Angular HttpInterceptor不更改标题 [英] Angular HttpInterceptor not changing header

查看:69
本文介绍了Angular HttpInterceptor不更改标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个有角度的(4.3.6)HttpInterceptor,以添加一些标头字段,但是如果在调试器中检查标头字段,则标头不会更新.有什么主意吗?

I wrote an angular (4.3.6) HttpInterceptor to add some header fields, but the header doesn't get updated if I inspect them in the debugger. Any idea?

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {


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

        console.log('AuthInterceptor at work');

        const contentTypeReq = req.clone({
            headers: req.headers.set('Content-Type', 'application/json')
        });

        const token  = localStorage.getItem('token');
        if (token) {
            const authReq = contentTypeReq.clone({
                headers: req.headers.set('Authorization', 'Bearer ' + token)
            });
            return next.handle(authReq);
        }

        // Pass on the cloned request instead of the original request.
        return next.handle(contentTypeReq);
    }
}

推荐答案

它们很懒.例如 keys方法看起来像:

They are lazy. For example keys method looks like:

keys(): string[] {
    this.init(); <== initialize

    return Array.from(this.normalizedNames.values());
}

如果要检查它们,只需致电:

If you want to check them just call:

req.headers.keys()

如果要检查值,可以使用getgetAll方法:

If you want to check value you can use get or getAll method:

req.headers.getAll('Content-Type')

或者您可以从控制台调用init方法,然后您将能够在headers地图中查看标题

Or you can call init method from console and then you will be able to see headers in headers Map

此外,当角度将标头添加到请求,它使用

Moreover when angular adds headers to request it uses forEach method that calls init method too.

这篇关于Angular HttpInterceptor不更改标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆