The HttpInterceptor is programmed to identify and capture 401 error responses

After successfully implementing a code that called a logout() method upon receiving a 401 response from the server, I encountered issues following an upgrade of Angular from 5.2 to 7.0.3. It seems like either the HttpInterceptor interface has been modified or there have been numerous rxjs breaking changes. The current implementation appears as shown below and results in the error specified under the code snippet.

export class UnauthInterceptor implements HttpInterceptor {

  private session: SessionProvider;
  constructor(private injector:Injector) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      this.session = this.injector.get(SessionProvider);
      return next.handle(request).pipe(catchError(err => {
        if (err.status === 401) {
            // auto logout if 401 response returned from api
            this.session.logout();
        }
    })
  );
}}

The TypeScript compiler throws the following error message:

src/app/interceptors/unauth.interceptor.ts:19:51 - error TS2345: Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable>) => ObservableInput<{}>'.
Type 'void' is not assignable to type 'ObservableInput<{}>'.

19 return next.handle(request).pipe(catchError(err => {

Answer №1

Hey there, make sure to include catchError in your observable like so:

return throwError(error)

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

Different Ways to Validate Angular 2 FormGroups

Component: ngOnInit() { this.record = new FormGroup({ movement: new FormControl(''), weight: new FormControl('', [Validators.required, Validators.pattern('^[0-9]*$')]), date: new FormControl('' ...

What is the best approach for utilizing Inheritance in Models within Angular2 with TypeScript?

Hey there, I am currently dealing with a Model Class Question and a ModelClass TrueFalseQuestion. Here are the fields: question.model.ts export class Question { answerId: number; questionTitle: string; questionDescription: string; } truefals ...

When trying to use global.mongoose in Typescript, a type error is being thrown

I'm attempting to incorporate caching into my database connection file in order to streamline the process for my next.js application and avoid repeating the connection step every time I interact with the database. import mongoose from 'mongoose&a ...

Enhance the angular 2 dependencies within the angular2-cli project

After experimenting with Angular 2 and following the guide on their website, I attempted to switch to Angular 2 CLI. However, the Angular 2 CLI project does not have the latest dependencies, resulting in errors from the compiler related to certain commands ...

Tips for retrieving an object from an array with Angular and Firestore

Currently, I am attempting to retrieve an object from Firestore using the uid so that I can return a specific object as a value. I have implemented a function in order to obtain the object 'Banana'. getFruit(fruitUid: string, basketUid: string) ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Creating an interactive form in Angular2 using *ngFor, implementing two-way data binding with [(ngModel)], and including form validation

Challenge Description I'm currently working on developing a dynamic form that can update parts of the interface based on changes in the underlying model: When a user clicks a button, a new entity is added to the internal list of components and a ne ...

What is the best way to showcase a variable from a typescript file in an HTML file with Angular?

In my TypeScript file, I have the following function: ngOnInit() { if (sessionStorage['loyalPage']) { this.page = Number(sessionStorage['loyalPage']); } this.webService.getLoyalPlayers(this.pag ...

The argument labeled as 'Subscription' cannot be assigned to the parameter labeled as 'string' in Angular

I am utilizing my Subscription variables to retrieve the API from configuration settings. public ChannelsAPI=this._configservice.getConfiguration("ChannelAPI").subscribe((result) => console.log(result)); This is the method _Configservice.getC ...

The concept of a generic type serving as a characteristic of an incoming argument

What is the best way to assign a type property of an argument to a generic in TypeScript? Here's the code snippet: const foo = <T = someObject.bar>(someObject: {[string]: any}): T => { return someObject.bar } How can we set the type of ...

What could be causing the excessive number of connections in my MongoDB instance?

This code snippet is crucial for my initial connection setup let cachedDbConnection: Db export async function establishDatabaseConnection(): Promise<{ db: Db }> { if (cachedDbConnection) { return { db: cachedDbConnection } } const client ...

Receiving multiple Firebase notifications on the web when the same application is open in multiple tabs

I have implemented firebase push notifications in Angular 7 using @angular/fire. However, I am facing an issue where I receive the same notification multiple times when my application is open in multiple tabs. receiveMessage() { this.angularFireMess ...

Update not reflecting in Angular Reactive Form custom component value

I've developed a custom input component that extends the primeng spinner component. However, I'm facing an issue with Angular Reactive Form where the model value of my component is not being updated. To make it easier to debug, I've created ...

The data set in a setTimeout is not causing the Angular4 view to update as expected

I am currently working on updating a progress bar while importing data. To achieve this, I have implemented a delay of one second for each record during the import process. Although this may not be the most efficient method, it serves its purpose since thi ...

The Angular Router is continuing to show the HomeComponent upon navigation, rather than just displaying the ChildComponent

Lately, I've been diving into Angular and attempting to create a github search application using the github api. However, I've encountered some roadblocks with routing and data passing. My goal is for the user to land on a page like /user/userID ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

Angular 8 @viewChild directive resulting in a null value

stripeService.ts @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef; stripe = Stripe(environment.stripe.pubKey); async initStripeElements() { const elements = this.stripe.elements(); const cardElement = e ...

Is there a way for me to showcase something in the console after clicking on an event in fullcalendar?

In the configuration: select: this.handleManualSelect.bind(this), dateClick: this.dateClick.bind(this), eventClick: info => { console.log(info, 'click'); }, eventMouseEnter: info => { console.log(inf ...

Encountering an endless loop within a data rest API in a React application

Currently, I am in the process of learning React and attempting to utilize the Poke API with my application. Unfortunately, I seem to have run into an infinite loop issue and I am feeling quite lost in terms of troubleshooting it. Below is a snippet of my ...

Guide on disabling a hyperlink in a table column under specific conditions using Angular2

I am working with a table that has 4 columns: Name, id, Dept, City. The row data and column data are provided as an array from a typescript file and I am iterating through *ngFor to display the content. Below is a snippet of my code: <tbody> < ...