Issue: The Auth Interceptor is expecting a stream but received 'undefined'. Please provide an Observable, Promise, Array, or Iterable instead

I am facing an issue where I need to intercept every request to api, check the status code, and display a message or redirect to a specific component. However, I keep encountering 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 have been unable to identify the line or block of code that is causing this error, as it is not mentioned in the error message. The project compiles without any issues, but this error occurs on almost every page whenever a request is sent to the WEB Api.

Answer №1

Don't forget to include the return statement in the else block. Make sure to add return next.handle(req.clone()); within the else block whenever

localStorage.getItem('currentUser')
is null.

Answer №2

Many people attribute this error to the presence of 'interceptors', which could be a valid explanation. However, I recently encountered the same TypeError without utilizing any interceptors in my Angular app (version 9.0.2) connected to a Firebase API. While working on a new component for managing contractors, I decided to use 'angular-in-memory-web-api' before saving data to the backend.

After adding the module 'InMemoryWebApiModule.forRoot(ContractorData)' to the 'imports' section of my App.Module, I faced difficulties accessing the API when trying to fetch another entity. The browser console displayed the following error:

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

My theory is that implementing the ImMemoryWebApiModule somehow interferes with the HttpClient process, potentially altering the request being sent to the API.

You can view a screenshot https://i.sstatic.net/1082z.png

I hope this information helps you troubleshoot your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Define an object by extracting properties from an array of objects

Is there a way to refactor this code to remove the need for explicit casting? type A={a:number}; type B={b:string}; let a:A={a:0}; let b:B={b:''}; function arrayToObject<T>(array:T[]):T { return array.reduce((r,c) =>Object.assign ...

Error: The element 'mdb-icon' is not recognized and cannot be parsed

I am currently utilizing Angular 7 alongside Bootstrap 4, and encountering the following error message in my console. Uncaught Error: Template parse errors: 'mdb-icon' is not a known element: If 'mdb-icon' is an Angular co ...

Checking for coverage in unit testing of the RxJS Observable catch block

I need to increase unit test coverage on a code block that includes a catch block calling a method to handle errors. Here's the code snippet in question: return this._http.get(/someurl) .map((response: Response) => { le ...

The reason for the Jest failure is that it was unable to locate the text of the button

As someone who is new to writing tests, I am attempting to verify that the menu opens up when clicked. The options within the menu consist of buttons labeled "Edit" and "Delete". However, the test fails with the message: "Unable to find an element with te ...

Display the modal in Angular 8 only after receiving the response from submitting the form

I am encountering an issue where a pop-up is being displayed immediately upon clicking the submit button in Angular 8, before receiving a response. I would like the modal to only appear after obtaining the response. Can someone assist me with achieving thi ...

The art of connecting with Angular 2 router and Components

Here are the elements I have: <app-scrollable-area (scrolledDown)="..." class="scrollable-y"> <router-outlet></router-outlet> </app-scrollable-area> I'm wondering how to communicate this event (scrolledDown) to inside ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

update a property of a live object using an API request

Below is a sample of the service function I am working with: getByIdWithCategory(id: number): Observable<Product> { const category = new Category(); category.name = 'sample category'; return this.httpClient.get<Product> ...

Accessing React.FC in Another File with TypeScript - A Step-by-Step Guide

code - const Exne: React.FC <IProps> = ({x}) => { console.log('input', x); const [getx, assignx] = useState(x); console.log(getx, assignx); return(getx) }; Could you please provide instructions on how to acc ...

How to add icons to HTML select options using Angular

Looking for a way to enhance my component that displays a list of accounts with not only the account number, but also the currency represented by an icon or image of a country flag. Here is my current component setup: <select name="drpAccounts" class= ...

Issue with Adding Class to Angular2 Material Tooltips

Here is the code from my component.html file: <tr> <td> <span matTooltipClass="primary-tooltip" matTooltipPosition="above" matTooltipHideDelay="100000" matTooltip="{{cert.awsCertId}}"><p style="overflow:hidden;text-overflow: ellip ...

Encountering the issue of receiving "undefined" in node.js after submitting data from an Angular form

I am facing an issue where I am getting 'undefined' in the backend (node.js) when I submit data from angular forms, even though I have used body-parser to parse the incoming data. server.js const express= require("express"); const app= ...

Capturing a webpage through Record RTC integration with Angular

I am looking to record a specific section of the page as a video with audio. For example, when a user enters the page, I want it to automatically start recording the activities in that particular area (similar to how iframe videos work). The recording sh ...

Extract TypeScript classes and interfaces from a consolidated file

I am seeking a way to consolidate the export of my classes, interfaces, and enums from multiple files into a single file. In JavaScript, I achieved this using the following method: module.exports = { Something = require("./src/something").default, ...

Angular/Typescript code not functioning properly due to faulty expressions

What could be causing my {{ expression }} to malfunction? I have exhausted all options, yet the web browser fails to recognize this {{ expression }} or properly bind it using ng-bind. Instead, it either displays the {{ expression }} as is or not at all. C ...

Transitioning menus in Ionic 2

I followed the instructions in the Ionic 2 menu documentation and tried to display the menu in a specific way: https://i.sstatic.net/zzm8f.png My intention was to have the menu displayed below the content page while keeping the menu button visible. Howe ...

execution of synchronized task does not finish

My approach to running Protractor tests in a headless mode using Xvfb may not be the most efficient, so let me outline my high-level requirement first. I am utilizing the angular2-seed and I aim to execute Protractor tests in a headless mode by incorporat ...

Using TypeScript with VSCode's Vetur Vue package may result in errors such as "Cannot locate symbol 'HTMLElement,' 'window,' or 'document'."

After much research, I'm still struggling with a minor Vetur issue in my Vue3 + ts setup. Despite trying various modifications to the tsconfig file recommended by others, none of them have resolved the warnings I'm encountering. I attempted to i ...

Tips for uploading the IDENTICAL file in angular4

After successfully uploading a file, I encountered an issue where the system does not allow me to upload the same file twice. Here is the code snippet related to the problem: <input type="file" (change)="onFileChange($event)" name="fileUploaded" value ...

The JSX component in next.js cannot be utilized as a user component

I am facing difficulty in getting my mobile menu to function properly. Initially, I attempted to position it above other content using the useEffect hook, but unfortunately, it resulted in breaking the entire project. This is the error message I encountere ...