【发布时间】:2019-07-07 18:48:59
【问题描述】:
我使用 Ionic 4 创建应用程序。我尝试实现一个 HttpInterceptor 来将承载授权令牌添加到请求中。
问题:在读取令牌之前发送请求
更多细节:
- 我尝试从本地存储中读取令牌
- 下面的console.log打印出token
怎么了?
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
token:any;
constructor(private router: Router,private storage: Storage) {
this.storage.get('User').then((val) => {
this.token = val;
console.log(val); // Returns the token
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.token); // Returns undefined
if (this.token) {
request = request.clone({
setHeaders: {
'Authorization': this.token
}
});
}
if (!request.headers.has('Content-Type')) {
request = request.clone({
setHeaders: {
'content-type': 'application/json'
}
});
}
request = request.clone({
headers: request.headers.set('Accept', 'application/json')
});
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('event--->>>', event);
}
return event;
}),
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
if (error.error.success === false) {
// this.presentToast('Login failed');
} else {
this.router.navigate(['/']);
}
}
return throwError(error);
}));
}
}
【问题讨论】:
-
我很好奇,如果你在构造函数和拦截函数中都放了一个console.log('{CODE_LOCATION}' + this.token),那会返回你的token吗?
-
@dmoore1181 它为构造函数返回它,但它在拦截函数中未定义。我更新了问题。
-
我只是简单地建议对所有 http 请求使用高级 http 插件。 ionicframework.com/docs/native/http
标签: javascript angular typescript ionic-framework ionic4