【发布时间】:2017-09-03 01:38:19
【问题描述】:
登录后我能够获取令牌的值,因为我从函数中传递了用户名和密码的值。在下一页上,我没有传递这些值。这对于为什么我得到 null 是有道理的 - 这是我没有将令牌返回包装在承诺中的时候。当我将令牌值包装在如下所示的 Promise 中时,我收到此错误 ERROR TypeError: Cannot read property 'then' of undefined, the token is undefined 这是因为我没有登录我需要生成令牌的用户凭据,因此它不存在或未定义。在用户登录之前,我将如何调用该函数。假设我在调用第二页时不会返回 null,因为就像我上面提到的那样,我包装了我的存储承诺返回。谢谢!
Auth.ts
login(userName: string, password: string, route: string = null): any {
this.logout(false);
this.doLogin(userName, password)
.subscribe(response => {
let token:string = JSON.stringify(response.access_token);
this.storage.set('token', token);
});
}
getToken() :any{
this.storage.get('token').then((val) => {
this.accessToken = val;
if(this.accessToken == null){
return '0'
}
else{
return "Bearer " + this.accessToken.replace(/["]+/g, '')
}
})
}
组件.ts
login(){
this.authService.login(this.account.username, this.account.password)
}
拦截器.ts
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let access = this.auth.getToken()
const authReq = req.clone({
setHeaders: {
Authorization: access
}
});
return next.handle(authReq)
}
谢谢!
【问题讨论】:
标签: angular ionic-framework ionic2