1
我能夠在登錄後獲取令牌的值,因爲我正在從函數傳入用戶名和密碼的值。在下一頁中,我沒有傳遞這些值。這對我爲什麼會變爲null是有道理的 - 這是我沒有在promise中包裝令牌返回的時候。當我在下面看到的承諾中包裝令牌值時,出現此錯誤錯誤TypeError:無法讀取未定義的屬性'then',令牌未定義這是因爲我沒有用我需要的用戶憑證登錄生成令牌,因此它不存在或未定義。我將如何去調用該函數,直到用戶登錄。假設我在撥打第二個頁面時不會返回null,因爲就像我上面提到的那樣,我封裝了我的存儲承諾返回。謝謝!本地存儲承諾未定義的值。 Ionic 2+/Angular 4.3
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, '')
}
})
}
component.ts
login(){
this.authService.login(this.account.username, this.account.password)
}
Interceptor.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)
}
謝謝!
問題在於我正在返回Promise >>而不是Observable >這是導致錯誤 –
userlkjsflkdsvm