The issue with HttpErrorInterceptor failing to redirect in an Angular application

I'm currently working on implementing a global error interceptor in my project. The idea is that whenever an error occurs, the user should be redirected to the main page with an error=true query parameter. However, despite successfully catching and logging the error, the redirect does not seem to be working. Can anyone point out what I might be doing wrong?

HttpErrorInterceptor:

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {

  constructor(private router: Router) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
      .pipe(
        catchError((error: HttpErrorResponse) => {
          let errorMsg = '';
          if (error.error instanceof ErrorEvent) {
            errorMsg = `Error: ${error.error.message}`;
          } else {
            errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
          }
          const urlParams = new URLSearchParams(window.location.search);
          this.router.navigate(['main'], {queryParams: {error: true, sesskey: urlParams.get('sesskey')}});
          console.log(errorMsg);
          return throwError(errorMsg);
        })
      )
  }
}

app.module.ts:

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true
    },

Answer №1

Seems like everything is running smoothly, have you checked the results?

This is how it's functioning for me

export class MainComponent {

  constructor(private apiService: ApiService) {
    this.fetchData();
  }

  fetchData() {
    const endpoint = 'Placeholder url';
    return this.apiService.get(endpoint).subscribe();
  }
}

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

Tips for merging an Observable containing a series of values with an Observable containing a single value and subsequently simplifying this arrangement

I am searching for the most efficient method to combine two functions that return Observables. The initial function is described as: abstract getProfiles(): Observable<ClientProfile[]> The other one is: abstract getUser(userId: number): Observabl ...

Using EmailValidator in Ionic 3

Recently, I noticed that the Angular dev team has introduced a new feature called EmailValidator in the latest Ionic framework update. However, I'm finding it a bit confusing on how to implement it. Can anyone provide me with an example of how to use ...

I am encountering difficulties installing Angular CLI due to error messages. Can you please provide me with a solution

Error encountered while running 'npm install -g @angular/cli': npm ERR! code ENOENT npm ERR! syscall mkdir npm ERR! path C:\Windows\system32'C:\Users\User\AppData\Roaming\npm' npm ERR! errno -4058 npm ...

Users will not receive notifications or see highlighted mentions

Lately, I've been experimenting with Discord.js and Typescript and came across an issue while trying to create a simple command that pings the user. However, instead of pinging them, it only mentions their username. Below is the code snippet I'm ...

Angular 2 and SystemJS: Dealing with the Challenge of Circular Dependencies

I have been struggling with a problem that seems to stem from a circular dependency. Despite conducting thorough research, I have not been able to find a suitable solution. It appears to be similar to the issue discussed here: TypeError: b is undefined in ...

Angular 4's async pipe triggers an endless loop when used in conjunction with a method call

How can I create a select UI element with dynamic options using a method that returns an observable based on the inputs provided? TypeScript (Component class) retrieveCars(type : string, engine : string) : Observable<Cars>{ return this.carServi ...

Is it possible to send React props to the next/image within a component?

I need assistance with creating a card component that utilizes next's Image component. However, the src prop on Image is not accepting the props that I am passing down. import React from 'react' import { Childs } from '../../interfaces/ ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Fix the static-class-block error when running Jest tests in TypeScript

Recently, I included the antlr4ng (version 3.0.4) package in my TypeScript project's package.json, which is based on Node.js version 20.11.1. It functions well except when used within a Jest test, where it throws this error at runtime: SyntaxError: /U ...

What is the best way to remove a polygon from an agm-map?

Is there a way to remove a polygon from the map when the clear button is clicked? <agm-map [latitude]="40.034989" [longitude]="29.062844" [zoom]="15" [agmDrawingManager]="drawing" class="full-width-height"> ...

What is the purpose of using @ViewChild to access a component's function from another component?

During a discussion with my tutor, I learned that in Angular we can utilize functions defined in any service by simply importing the service. However, unlike services, components cannot be directly imported into other components. To access a function from ...

Using Angular to create a nested routerLink within a routerLink

Is there a way to dynamically change the content of a page loaded using router link without duplicating the HTML code for the header and footer sections each time? I want to navigate between different pages with routerLink and have only the main content ar ...

JavaScript's Array.map function failing to return a value

Here is a snippet of code from an api endpoint in nextJS that retrieves the corresponding authors for a given array of posts. Each post in the array contains an "authorId" key. The initial approach did not yield the expected results: const users = posts.ma ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

How can one module call another module within Angular versions 4, 5, or 6?

What is the optimal folder structure for managing large Angular projects? 1) Is it possible for a module to call another module? If so, what is the limit on the number of sub modules within one module? 2) Can a sub module in one module call a module that ...

Angular: Automatically navigate to the parent page if the child parameter ID is missing

I currently have two separate modules with their own unique routing setups: CarsModule PassengersModule (Lazy Loaded) Passenger is essentially a child of car and can be accessed through the following URL structure: https://localhost/cars/12/passengers/1 ...

Angular: directive modifying the value of a form control

I have implemented a feature to automatically transform the slug when the user inputs the name in a control field. This transformation includes changing spaces to hyphens (-) among other things. Although I created a directive for this purpose, it seems to ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Configuring Auth0 for a sub-application within an Angular framework

Our main Angular application is set up with Auth0 for authentication. Within this main application, we have a sub-application imported as an npm module. This sub-application also has its own standalone deployable version used for development and testing pu ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...