解决HttpInterceptor中的promise

时间:2018-02-18 18:20:18

标签: angular ionic-framework ionic2 rxjs angular-http-interceptors

我正在使用离子原生插件 SecureStorage 来安全地保存身份验证令牌。现在,我想在HttpInterceptor中访问它并将其附加到HttpRequest的Headers:

let duplicate = request.clone({
headers: new HttpHeaders({
    'Authorization': token
})

所以我调用一个函数来获取一个有效的令牌,它(减少了到期日期检查)看起来像这样:

  getValidToken(): any {
    return new Promise(resolve => {
      this.secureStorage.create('login_data').then((storage: SecureStorageObject) => {
        storage.get('token').then(data => {
          resolve(data);
        });
      });
    });
  }

不幸的是,我不断收到错误消息“您提供的'未定义',其中包含一个流。您可以提供Observable,Promise,Array或Iterable ”。在这种情况下我该如何处理?

这是我完整的“拦截”方法实现:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    this.loginProvider = this.injector.get(LoginProvider);  // avoid cyclic dependency errors, cf. https://github.com/angular/angular/issues/18224
    this.getValidToken().then(token => {
      let duplicate = request.clone({
        headers: new HttpHeaders({
          'Authorization': token
        })
      });
      return next.handle(duplicate).do((event: HttpEvent<any>) => null, (error: any) => {
        if (error instanceof HttpErrorResponse)
        if (error.status === 401 || error.status === 403)
        /* redirect to login, username/password do not match anymore */
        this.injector.get(NavController).setRoot(LogoutPage);
      });
    })
  }
在此之前,我只是使用html5 localStorage并使用“let token = localStorage.getItem('token')”从那里检索令牌,并且它工作得很好:(

非常感谢!!

1 个答案:

答案 0 :(得分:0)

您是否忘记了函数定义中的return

恕我直言,在另一个Promise中包装是不必要的,以下简化代码应该适合你:

getValidToken(): any {
    return this.secureStorage
        .create('login_data')
        .then((storage: SecureStorageObject) => storage.get('token'));
        // will return a Promise that resolves to the return value of
        // storage.get(), which is another Promise that resolves to "data"
}