Capturing HttpErrorResponse and automatically navigating user to login page

My objective is to automatically redirect users to the login page whenever a login attempt fails. I have implemented an interceptor to manage Http responses:

export class HttpInterceptor implements HttpInterceptor { 
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    return next.handle(request).do((event: HttpEvent<any>) => {}, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        console.log("Intercepted HTTP error")
      }
    });
  }
}

However, I encountered an error stating "property do does not exist on type observable>". I'm also unsure how to redirect users back to the login page from the interceptor. Can anyone provide guidance on how to resolve this issue? Your assistance is greatly appreciated, thank you!

Answer №1

Here's an illustration of what you're aiming for, utilizing the pipe and the more recent tap operator instead of the deprecated do operator.

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent,
    HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class HttpInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(
        event => event instanceof HttpResponse ? 'succeeded' : '',
        error => {
          if (error instanceof HttpErrorResponse) {
            console.log('http error intercepted')
          }
        })
    );
  }
}

Note: This code compiles successfully, but it has not been tested yet.

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

Avoiding useCallback from being called unnecessarily when in conjunction with useEffect (and ensuring compliance with eslint-plugin-react-hooks)

I encountered a scenario where a page needs to call the same fetch function on initial render and when a button is clicked. Here is a snippet of the code (reference: https://stackblitz.com/edit/stackoverflow-question-bink-62951987?file=index.tsx): import ...

Exploring the contrasts and practical applications of Virtual Scroll versus Infinite Scroll within the framework of Ionic 3

After thoroughly reviewing the documentation for Ionic 3, I embarked on a quest to discern the disparity between https://ionicframework.com/docs/api/components/virtual-scroll/VirtualScroll/ and https://ionicframework.com/docs/api/components/infinite-scr ...

NodeJS and Angular2 application experiencing loading issues

Currently, I am diving into the world of Angular2 and thanks to the quick start guide provided on their official documentation, I have successfully set everything up. However, if I plan to work with APIs on the server or host my project in the cloud, it ap ...

Having trouble with testing an Angular directive?

This is a snippet from my directive spec file for Angular 6. import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { TestBed, ComponentFixture, async } from '@angular/core/testing'; import { By } from ' ...

Angular failing to render data in user interface

Exploring the concept of CRUD Operations, I am attempting to implement basic CRUD operations using Angular for the front end and Web API for the back end. The API is quite straightforward, returning a simple JSON structure as shown below: [ { "stud ...

Navigating TS errors when dealing with child components in Vue and Typescript

Recently, I encountered an issue where I created a custom class-based Vue component and wanted to access its methods and computed properties from a parent component. I found an example in the Vue Docs that seemed to address my problem (https://v2.vuejs.org ...

Exploring Angular - Is it possible to automate testing for a disabled field using Selenium Protractor?

For my MEAN stack project, I am implementing Selenium webdriver to conduct frontend UI testing. There is a field that is non-editable. Please refer to the attached image: Image How can I verify that this field cannot be edited? it('not edit th ...

AngularDart's runtimeType object

My component is designed to accept a model object, but the type of this object determines which specific component will be rendered inside: <div [ngSwitch]="poolModel.runtimeType.toString()"> <template ngSwitchCase="CryptonoteMiningPool">& ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

The Jest test encounters failure when attempting to use an absolute path to load an SVG image

Currently, I am developing a Typescript React application using Vite. To test my app, I have implemented Jest and babel. An important aspect of my setup is the use of absolute paths throughout the entire application. Interestingly, when I run tests with r ...

Using Typescript to create a mapped type that allows for making all properties read-only, with the exception of

I encountered a problem where I didn't want to repeatedly rewrite multiple interfaces. My requirement is to have one interface with full writing capabilities, while also having a duplicate of that interface where all fields are set as read-only excep ...

How can I receive updates when an interface changes in Angular?

I'm attempting to subscribe to my interface and monitor for any changes, but I keep encountering errors. Fetching data from the API and assigning it to this.candidateProfile : export interface CandidateProfile { about: string, c_id: {}, cer ...

The issue with Angular's "let-col" directive is that it does not successfully pass along every property

Extra fields have been implemented to aid in processing tasks. Below is how the columns array is defined: this.columns = [ {field: 'vin', header: 'Vin', isMultiRowColumn: true }, {field: 'year', header: ' ...

Define two categories within the Attributes interface

To avoid theme-ui errors in the sx prop, I need to declare both of these statements: declare module "react" { interface Attributes { sx?: ThemeUIStyleObject; } } and declare module "react" { interface Attributes { sx?: Sx ...

Setting input autofocus in a recursive Angular2 component

Currently, I am working on creating a tree view system similar to Workflowy for practice purposes. The simple version is operational; however, I am facing difficulty in setting the input focus when adding a new component. I have experimented with various ...

Utilize Angular-Material to showcase a tooltip when hovering over a form label

I am struggling to display a tooltip on a label. Is there an easy fix for this issue? <mat-form-field> <mat-label matTooltip="Please enter your E-Mail Address"> E-Mail <mat-icon>help_outline</mat-icon> < ...

Encountering a TypeScript error within the queryFn while implementing Supabase authentication alongside React Toolkit Query

I've been attempting to integrate Supabase authentication with React Toolkit Query but encountering an issue with the utilization of the queryFn. Here is the code snippet that employs supabase.auth.signUp to register a user using email/password. You ...

Struggling with making `http.get` function properly in Angular 2

Attempting to execute a basic GET request using Http in Angular 2, following guidance from this TUTORIAL and other current resources. Upon successfully injecting the http component, the following code was implemented constructor(@Inject(Http) /* remove ...

The ng2-image-viewer does not support the newest versions of Angular (11 and above)

Encountering an issue with ng serve: Error message: ERROR in node_modules/ng2-image-viewer/index.d.ts:3:22 - error NG6003: Appears in the NgModule.exports of SharedModule, but could not be resolved to a NgModule, Component, Directive, or Pipe class. This ...