Angular 4自定义http拦截器。 localStorage.getItem()返回null

时间:2017-08-31 15:53:55

标签: html5 angular local-storage typescript2.0 angular-http-interceptors

我正在使用Azure B2C身份验证。成功重定向后,访问令牌存储在浏览器的localStorage中,对于后续的API调用,http拦截器类应该将auth令牌附加到所有出站请求。问题是localStorage.getItem()在尝试从localStorage读取auth令牌时返回null。这是代码,

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

@Injectable()
export class HttpManagerInterceptor implements HttpInterceptor {

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
    req = req.clone({ headers: req.headers.set('X-CRSP-TOKEN', 'ToBeImplemented') });

    // this line always returns null
    const authToken = window.localStorage.getItem('auth_token');

    console.log('Inside http interceptor. Access token: ' + authToken);
    if (authToken) {
        req = req.clone({ headers: req.headers.set('Authorization', `Bearer 
        ${authToken}`) });
    }

    console.log(JSON.stringify(req.headers));
    return next.handle(req);
 }

控制台日志
令牌发现:
  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ilg1ZVhrNHh5b2pORnVtMWtsMll0djhkbE5QNC1jNTdkTzZRR1RWQndhTmsifQ.eyJpc3MiOiJodHRwczovL2xvZ2luLm1pY3Jvc29mdG9ubGluZS5jb20vYmY5Njg3YWYtOTliMy00YzU3LWI2YjAtOWE5OGIzNTRhOWQyL3YyLjAvIiwiZXhwIjoxNTA0MTMxNzM3LCJuYmYiOjE1MDQxMjgxMzcsImF1ZCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsIm9pZCI6IjcyMzljZWVjLTMzN2ItNDlmNS04YzViLTVkMzcwZGEwZmIxOCIsImdpdmVuX25hbWUiOiJaZWVzaGFuIiwiZmFtaWx5X25hbWUiOiJIYWlkZXIiLCJzdWIiOiJOb3Qgc3VwcG9ydGVkIGN1cnJlbnRseS4gVXNlIG9pZCBjbGFpbS4iLCJlbWFpbHMiOlsiWmVlc2hhbi5IYWlkZXJAY3JzcC5jaGljYWdvYm9vdGguZWR1Il0sImF6cCI6IjI4ZGM0NjZkLWRhZGUtNDNkMy04ZjBhLTJkYmNlNTQxYmIxMyIsInZlciI6IjEuMCJ9.DUebFoHuzLXIbjMOmRrCRYswMB1g-7J6kVOaYyI3-b5AuaTjrcTtTsZkiGbloseaKqKtKoRtO72EkyQ2XvJ2lyhCBybpD4skeOcwQ2p_RBcO1dlFSoWIOkQK7WPN_f3tLxzuvKgrcPuR2LurB_n0uEq8PTdMIKXgfuCVDUSjxGrcwlzGi61k2g24wzO-u9YdN5Xqx0eFqooE0hhiifTsAsXPNJhXTmLinr4qt25bRfvVs1UpYNk6hv1RQ3afrg7UZavr-Osjh5amQ6Qi_q6kKTQWorB9Cgoj_UTIA8ojkK-6y7D8uzY-YtLzomuNvD8mELCeZC8ZdPbbibzC2Kj6Rw < / P>

内部http拦截器。访问令牌:null

我怀疑在localStorage可用之前是否初始化或创建了INTERCEPTORS。如果是这种情况并且没有解决方法,那么有人可以建议其他解决方案吗?

我们将非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在组件内部注入窗口

@Inject(WINDOW) private window: any