登录后,我能够从本地存储中获取令牌。之后,我需要从标头响应中获取令牌,因为我需要在较早的令牌过期之前再次存储新令牌。
下面是我的拦截文件:
import { environment } from './../../environments/environment';
import { Injectable, Inject } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
HttpResponse,
HttpHeaderResponse,
HttpClientModule
} from '@angular/common/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/empty';
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(private router: Router) { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const token = this.getToken(); //first token after signin
const JWT = `Bearer ${token}`;
req = req.clone({
setHeaders: {
Authorization: JWT
}
});
req = req.clone({ url: this.prepareUrl(req.url) });
return next.handle(req)
.do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log(event); //here I am checking for a new
token in event but unable to get that.
}
})
.catch((error, caught) => {
//intercept the response error and displace it to the console
console.log(error);
if (error instanceof HttpErrorResponse) {
if (error.status === 401) {
// redirect to the login route
this.router.navigate(['/login']);
}
else if (error.status === 0) {
// Show the error message
return Observable.empty<HttpEvent<any>>();
}
}
//return the error to the method that called it
return Observable.throw(error);
}) as any;
}
private isAbsoluteUrl(url: string): boolean {
const absoluteHttpPattern = /^http?:\/\//i;
const absoluteHttpsPattern = /^https?:\/\//i;
return absoluteHttpPattern.test(url) || absoluteHttpsPattern.test(url);
}
private prepareUrl(url: string): string {
url = this.isAbsoluteUrl(url) ? url : environment.api + url;
return url.replace(/([^:]\/)\/+/g, '$1');
}
getToken(): string {
return localStorage.getItem('accessToken');
}
}
以下是我收到的日志响应:
HttpResponsebody: Array[2]headers: HttpHeaderslazyInit: ()lazyUpdate: nullnormalizedNames: Map__proto__: Objectok: truestatus: 200statusText: "OK"type: 4url: null__proto__: HttpResponseBase
当我打开开发人员工具时,我能够看到响应头,但在我的拦截文件中却没有。
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Tue, 11 Dec 2018 13:16:54 GMT
Expires:0
Pragma:no-cache
t:eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbkBuZXRhcHAuY29tIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiIxIn1dLCJpc3MiOiJodHRwOi8vY3JvLm5ldGFwcC5jb20iLCJpYXQ (I need to get this "t" value in my intercept file)
Transfer-Encoding:chunked
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block