Resolve promise inside HttpInterceptor

Hi guys,

I’m using the ionic-native Plugin SecureStorage to save an authentication token securely. Now, I want to access it inside an HttpInterceptor and append it to the Headers of the HttpRequest:

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

so I call a function to fetch a valid token, which (reduced the expiration date checkup) looks like that:

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

Unfortunately, I keep getting the error message “You provided ‘undefined’ where a stream was expected. You can provide an Observable, Promise, Array or Iterable”. How shall I proceed in this case?

Here is my complete “intercept” method implementation:

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 logout, username/password do not match anymore */
        this.injector.get(NavController).setRoot(LogoutPage);
      });
    })
  }

many thanks!!

99.9% of the time this construction is the explicit promise construction antipattern. If you find yourself typing this, alarm bells should go off. Between that and using any, you are pushing compile-time errors into runtime errors that are hard to debug. I suggest you strongly type all your variables and functions, use promises without explicit construction, and your error will probably become obvious. You will no longer be able to provide something undefined.

1 Like

thanks for the advice!

solved this issue using this thread: https://stackoverflow.com/questions/45978813/use-a-promise-in-http-interceptor