Search code examples
angulartypescriptobservableangular8angular-http-interceptors

Error: "You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable." in my Auth Interceptor


I want to intercept every request to api and check the status code so that it can display a message or redirect to a specific component, but it is giving the following error:

main.js:1580 TypeError: You provided 'undefined' where a stream was expected. You can provide an >Observable, Promise, Array, or Iterable.at subscribeTo (vendor.js:179688)at subscribeToResult(vendor.js:179824) at MergeMapSubscriber._innerSub (vendor.js:175271) at mergeMapSubscriber._tryNext (vendor.js:175265) at MergeMapSubscriber._next (vendor.js:175248) at MergeMapSubscriber.next (vendor.js:170316) at Observable._subscribe (vendor.js:172287) at Observable._trySubscribe (vendor.js:169772) at Observable.subscribe (vendor.js:169758) at MergeMapOperator.call (vendor.js:175233)

This is my AuthInterceptor:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { tap } from 'rxjs/operators'; 
import { CommonService } from '../common.service';
import { Router } from '@angular/router';
import { AuthenticationService } from './authentication.service';


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

  constructor(
    private common: CommonService,
    private router: Router,
    private auth: AuthenticationService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.get('No-Auth') === 'True') {
      return next.handle(req.clone());
    }
    // To attach header on every request
    if (localStorage.getItem('currentUser') != null) {
      const clonedreq = req.clone({
        headers: req.headers.set('Authorization', 'Bearer ' + localStorage.getItem('currentUser'))
      });
      return next.handle(clonedreq).pipe(tap(
        succ => { },
        err => {
          if (err.status === 401) {
            this.router.navigateByUrl('/login');
          } else if (err.status === 403) {
            this.router.navigateByUrl('/Forbidden');
          } else if (err.status === 400) {
            this.router.navigateByUrl('/error404');
          }
        }
      ));
    } else {
      this.router.navigateByUrl('/login');
    }
  }
}

I can't figure out the line or block which is causing it, as it is not written any where in the error. The project is compiled just fine. this error is shown in almost every page of the project where a request is sent to WEB Api.


Solution

  • In the else block you are missing the return statement. Add return next.handle(req.clone()); in else block when localStorage.getItem('currentUser') is null