I wanted to use interceptor to attach token to the request header. The token is stored using @ngx-pwa/local-storage which returns the token through Observable.

ERROR TypeError: "You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable."

I'm facing this error through the following code -

import { finalize } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { catchError, tap, map } from 'rxjs/operators';

import { LocalStorage } from '@ngx-pwa/local-storage';
import { User } from '../models/user';

@Injectable({
    providedIn: 'root'
})
export class httpInterceptorTokenService implements HttpInterceptor {

    constructor ( private localStorage: LocalStorage ) {  }

    private isAuthError(error: any): boolean {
      return error instanceof HttpErrorResponse && error.status == 401;
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      let intialRequest = req.clone();

      return next.handle(req).pipe(
        catchError((error) => {
          if (!this.isAuthError(error)) {
            return Observable.throw(error);
          }

          this.localStorage.getItem<User>('user').subscribe((userData:User) => {
            intialRequest = intialRequest.clone({
              setHeaders: {
                'Authorization': userData.token
              }
            });
            return next.handle(intialRequest).pipe(tap(res => res));
          }); // LOCAL-STORAGE
        })
      ); // RETURN
    } // INTERCEPT
} // EXPORT

Is there a solution to this or is there an alternate way to attach token to the header for every XHR?

1 Answers

0
Community On

The reason of the error is you are not returning an observable when it is an auhorization error. The return statement is inside a subscription block. Additionally as @jriver27 pointed, you are adding the request headers where you pipe for handling an error response. You need to handle it before the http call is made.

intercept(request: HttpRequest<any>, next: HttpHandler):   Observable<HttpEvent<any>> {
    let result: Observable<HttpEvent<any>> =    next.handle(this.addHeaders(request));
    return result;
}

private addHeaders(request: HttpRequest<any>):   HttpRequest<any> {
    const alteredRequest = request.clone({
      setHeaders: {
        Authorization: `Dummy-Auth   ${this.getDummyToken()}`
            }
    });
    return alteredRequest;
}