2017-09-01 44 views
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) 
    } 

謝謝!

回答

0

promise方法中的返回語句不起作用。 storage.get()是一個承諾,它是一個異步函數,所以value return在這裏不起作用。您可能需要將回調函數傳遞給getToken方法,並在then()函數內調用它,或者必須在Interceptor.ts中的get方法的then()函數中寫入截取邏輯。

+0

問題在於我正在返回Promise >>而不是Observable >這是導致錯誤 – userlkjsflkdsvm