我正在使用Ionic-Native插件 Securestorage 安全地保存身份验证令牌。现在,我想在httpintecceptor中访问它,并将其附加到httprequest的标题:
let duplicate = request.clone({
headers: new HttpHeaders({
'Authorization': token
})
所以我调用一个函数来获取有效令牌,该功能(减少了到期日期检查(看起来像:
getValidToken(): any {
return new Promise(resolve => {
this.secureStorage.create('login_data').then((storage: SecureStorageObject) => {
storage.get('token').then(data => {
resolve(data);
});
});
});
}
不幸的是,我不断收到错误消息" 您在期望流中提供了'Undefined'。您可以提供可观察的,承诺,数组或疑问>"。在这种情况下我该如何进行?
这是我完整的"拦截"方法实现:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.loginProvider = this.injector.get(LoginProvider); // avoid cyclic dependency errors, cf. https://github.com/angular/angular/issues/18224
this.getValidToken().then(token => {
let duplicate = request.clone({
headers: new HttpHeaders({
'Authorization': token
})
});
return next.handle(duplicate).do((event: HttpEvent<any>) => null, (error: any) => {
if (error instanceof HttpErrorResponse)
if (error.status === 401 || error.status === 403)
/* redirect to login, username/password do not match anymore */
this.injector.get(NavController).setRoot(LogoutPage);
});
})
}
在此之前,我只是使用html5 localstorage,然后使用" let token = localStorage.getItem('token'(从那里检索令牌",它效果很好:(
非常感谢!
您是否忘记了函数定义中的return
?
IMHO包装在另一个诺言内是不必要的,以下简化的代码应适用于您:
getValidToken(): any {
return this.secureStorage
.create('login_data')
.then((storage: SecureStorageObject) => storage.get('token'));
// will return a Promise that resolves to the return value of
// storage.get(), which is another Promise that resolves to "data"
}