Angular HttpInterceptor没有改变标题

时间:2017-09-26 05:53:01

标签: angular angular-http-interceptors

我写了一个angular(4.3.6)HttpInterceptor来添加一些头字段,但是如果我在调试器中检查它们,标题就不会更新。有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

他们很懒惰。例如keys method看起来像:

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

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

如果您想查看它们,请致电:

req.headers.keys()

如果您想查看价值,可以使用getgetAll方法:

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

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

enter image description here

此外,当angular adds headers to request使用调用init方法的forEach方法时。