The navigation function in Angular, this.router.navigate, is causing issues and

I've encountered a peculiar issue.

There's a logout function that is activated whenever I receive a 401 response from any API I interact with.

The function looks like this:

constructor(
    private router: Router,
  ) {}

logout(router1: Router) {
this.refreshTokenInProgress = false;
PreAngular.clearAll();
localStorage.clear();
if (window.location.href.indexOf("/public/login") == -1) {
  router1.navigate(["/public/login"]);
}
}

This logout function is called in the following manner:

  sendRequest(
    request: HttpRequest<any>,
    next: HttpHandler,
    isCacheable: Boolean,
  ) {
    return next.handle(request).pipe(
      catchError((error) => {
        if (error.status === 401 || (error.error != null && error.error.code == "0101")) {
          this.logout(this.router);
          //
          return throwError(error);
        }
      }),
    );

In my app, the scenario revolves around forcefully logging out a user from the database. If they are logged out and attempt to access any API, they receive a 401 response. My intention is for them to be logged out immediately upon receiving a 401 response. However, instead of logging out, an error is thrown in the typescript file of the page I am trying to route to after the forced logout. For example, an error is thrown on the ngOnInit function below:

ngOnInit() {
    this.activeUserListingForm = this.createFormGroup();
    this.isLogin = PreAngular.getUserInfo();
    this.manager = "manager";

    this.loadData();
  }
loadData() {
    this.formInProgress = true;
    this.usersService
      .getActiveUsersListing(
        this.skip / this.pageSize,
        this.pageSize,
        this.buildSearchParameters(),
        this.activeUserListingForm?.controls["searchInput"].value,
        this.dynamicColumns,
        this.sort,
      )
      .subscribe(
        (response) => {
          this.gridData = response;
          console.log(this.gridData);
          this.formInProgress = false;
          if (!response) this.toastr.error("Error", "No Record Found");
        },
        (err) => {
          console.log("Here in error" + err);
          this.toastr.error("Something went wrong");
        },
      );
  }

The console displays:

Here in errorTypeError: router1.navigate is not a function

The loadData function is in xyz.ts, which is the typescript file of the page I'm attempting to open after the forced logout, while the above code pertains to oauth.ts.

The aforementioned lines run in xyz.ts containing the loadData function:

  console.log("Here in error" + err);
  this.toastr.error("Something went wrong");

Upon applying a debugger, all the lines above the logout line execute successfully, but an error occurs on the this.router.navigate line.

Any advice or suggestions moving forward would be greatly appreciated.

Edit:
The error originates from the API file that I'm attempting to access. The aforementioned loadData code pertains to a sample API, so the error isn't consistently thrown in the same file. It depends on which API is being called.

Answer №1

In order to successfully execute the function, you must provide the router as a parameter. Here is an example of how to do this:

  logout(router: Router) {
    debugger
    this.refreshTokenInProgress = false;
    PreAngular.clearAll();
    localStorage.clear();
    if (window.location.href.indexOf("/public/login") == -1) {
      router.navigate(["/public/login"]);
    }
  }

To utilize the router within a functional guard, follow this approach:

sendRequest(
    request: HttpRequest<any>,
    next: HttpHandler,
    isCacheable: Boolean,
  ) {
    return next.handle(request).pipe(
      catchError(this.catchErrorHandler.bind(this)),
    );

catchErrorHandler(error) {
        if (error.status === 401 || (error.error != null && error.error.code == "0101") {
          this.logout(this.router);
          //
          return throwError(error);
        } 
      }

If the router object is not defined and you are using a functional guard, you can only inject it at the top level of the interceptor function or class like so:

    const router = inject(Router); // applicable for functional interceptor only

For cases where a normal class is being used, make sure to include the router in the constructor:

constructor(
...
private router: Router,
...
) {}

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

Reusing Angular routes across different modules for backbutton functionality

Insights on my Application (Angular 12): Comprises of 3 Modules, each containing an overview page with a list and specific detail pages Each route is assigned an area tag to identify the user's navigation within the module Goal for Angular´s RouteR ...

How can a child component class in Angular 2 be initialized when extending a parent class?

Let's consider a scenario where we have a component called ChildComponent that extends from the Parent class. How do we go about initializing the ChildComponent class? In Angular 2, when this component is used in HTML, it automatically invokes the Chi ...

Developing a Generic API Invocation Function

I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api - which represents the name of the API, route - the specific route within the 'api', and params - a JSON ...

Detecting Changes in Angular2 Component Attributes via Observables

When working with Angular 2 components that have input attributes defined using @Input, how can I create an observable to track changes to those input attributes (not to be confused with user input from a form)? export class ExampleComponent implement OnC ...

Replacing the previous observation

My events app features an all-events component that showcases all the events created. Upon loading the all-events component, the events are fetched from the database. Below is a snippet of the relevant code from the Typescript file of the all-events compo ...

Angular 5: Ensure Constructor Execution Occurs Prior to Injection

I am working with a file that contains global variables: @Injectable() export class Globals { public baseURL:string; public loginURL:string; public proxyURL:string; public servicesURL:string; constructor(platformLocation: PlatformLocation) { ...

Clicking on the Angular custom accordion component does not trigger the expansion feature

I have developed a customized accordion component using Angular 9, but I am encountering an issue. Whenever I click on the accordion, only the first button's window expands while the others remain unaffected. To demonstrate the problem more effective ...

Is there a way to efficiently execute an API function for every element within an array in a sequential manner?

I am currently facing a challenging problem while working with Angular and RxJs. I have an array containing several IDs: ids = [1,2,3,4] There is an API that can be called with a specific ID parameter to delete the corresponding item from the database: th ...

What is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

Angular: bypassSecurityTrustHtml sanitizer does not render the attribute (click)

I'm facing an issue where a button I rendered is not executing the alertWindow function when clicked. Can anyone help?: app.component.ts: import { Component, ElementRef, OnInit, ViewEncapsulation } from '@angular/core'; import ...

The proxy request gets delayed unless I utilize the http-proxy-middleware

Here is the code for a provider: @Injectable() export class GameServerProxyService { private httpProxy: httpProxy; constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) { this.httpP ...

Alert for timeout triggered without any error logs recorded

While working on a login & register page, I encountered an issue. After clicking the register button, a timeout alert error appeared despite no log errors being present. However, the data used to register was successfully saved in the MYSQL database. ...

The functionality of connect-flash in Express JS is compromised when used in conjunction with express-mysql-session

I am facing a unique issue in my project. I have identified the source of the problem but I am struggling to find a solution. My project utilizes various modules such as cookie-parser, express-mysql-session, express-session, connect-flash, passport and m ...

What is the best way to play AudioBuffer on an iPhone device?

When retrieving audio data from a stream, I encounter an issue with playing audio on iPhone Safari. The sound does not play unless I allow mediaDevice access for audio. Is there a way to play the audio without having to grant this permission? This is the ...

A More Straightforward Approach to Unsubscribing from Observables in Angular 7

Is there a way to simplify the process of automatically unsubscribing from Observables when a component is destroyed using takeUntil? It becomes tedious having to repeat the same code in multiple components. I am looking for a solution that allows me to a ...

Leveraging the power of Javascript and Firebase within the Angular framework

When attempting to integrate Firebase with Angular, I encountered an issue where my localhost was not able to function properly with my JavaScript code. The strange thing is that everything works fine when the code is placed directly in the index.html file ...

forwarding within afterCallback employing nextjs-auth0

I need to handle multiple cases for redirecting users based on various fields and custom claims in the user token, which involves navigating through complex if/else blocks. Let's consider a simpler example where I want to redirect the user to /email- ...

The Rxjs `of` operator fails to emit a value when utilizing proxies

I ran into an issue with a basic unit test that utilizes Substitute.js (I also tried using TypeMoq mocks, but encountered the same behavior). My test simply tries to use the of operator to emit the mocked object. Surprisingly, without any additional opera ...

How can I display the values stored in an array of objects in Angular 2

I need help printing out the value of id from an array that is structured like this: locations = [ {id: '1', lat: 51.5239935252832, lng: 5.137663903579778, content: 'Kids Jungalow (5p)'}, {id: '2', lat: 51.523 ...

Preventing data binding for a specific variable in Angular 2: Tips and tricks

How can I prevent data binding for a specific variable? Here's my current approach: // In my case, data is mostly an object. // I would prefer a global solution function(data) { d = data; // This variable changes based on user input oldD = da ...