0

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

before that, I simply used the html5 localStorage and retrieved the token from there using "let token = localStorage.getItem('token')" and it worked just fine :(

many thanks!!

Adrian Baginski
  • 336
  • 1
  • 8

1 Answers1

0

Didn't you forget the return inside the function definition?

IMHO the wrapping inside another Promise is unnecessary and the following simplified code should work for you:

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"
}
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30
  • Note that the above is different from your original `.then((storage: SecureStorageObject) => { storage.get('token') .... })` which probably resolves to `undefined`, because there is no `return`. – Stefan Becker Feb 18 '18 at 18:31
  • No sorry, that won't work. I think that the solution to this problem has something to do with the fromPromise 'rxjs/observable/fromPromise' function, but I can't implement that correctly either. – Adrian Baginski Feb 18 '18 at 18:39