【问题标题】:Undefined value from local storage promise. Ionic 2+ / Angular 4.3来自本地存储承诺的未定义值。离子 2+ / 角度 4.3
【发布时间】: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


    【解决方案1】:

    promise 方法中的返回语句不起作用。 storage.get() 是一个承诺,它是一个异步函数,因此值返回在这里不起作用。您要么需要将回调函数传递给 getToken 方法并在 then() 函数中调用它,要么必须在 Interceptor.ts 中 get 方法的 then() 函数中编写拦截逻辑。

    【讨论】:

    • 问题是我返回 Promise>> 而不是 Observable> 导致错误
    猜你喜欢
    • 2017-02-07
    • 2018-01-17
    • 1970-01-01
    • 2020-02-10
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多