本地存储承诺未定义的值。 Ionic 2+/Angular 4.3

问题描述:

我能够在登录后获取令牌的值,因为我正在从函数传入用户名和密码的值。在下一页中,我没有传递这些值。这对我为什么会变为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方法中的返回语句不起作用。 storage.get()是一个承诺,它是一个异步函数,所以value return在这里不起作用。您可能需要将回调函数传递给getToken方法,并在then()函数内调用它,或者必须在Interceptor.ts中的get方法的then()函数中写入截取逻辑。

+0

问题在于我正在返回Promise >>而不是Observable >这是导致错误 – userlkjsflkdsvm