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

Navigating away from an Ionic 2 app running in the browser and then returning: tips and tricks

Currently, I am setting up my oauth2 authentication in Ionic2. Through my research, I have discovered that the Cordova InAppBrowser plugin can be utilized to handle the process of navigating to the website and granting access to the App. However, I am st ...

A guide to implementing unit tests for Angular directives with the Jest testing framework

I am currently integrating jest for unit testing in my Angular project and I am relatively new to using jest for unit tests. Below is the code snippet for DragDropDirective: @HostListener('dragenter',['$event']) @HostListener(& ...

The RazorPay callback encountered an Uncaught TypeError indicating that the function is not recognized

In my TypeScript class, I have a defined handler as follows: "handler": function (response) { this.sendUserStatus(); }, Unfortunately, when I attempt to call this.sendUserStatus();, I encounter the following error: Uncaught Typ ...

What is the best way to retrieve both the checked and unchecked values from a collection of checkboxes?

Check Out This live Example: I am in the process of creating a list of checkboxes with various data objects: data = [ { Key: "class_id", displayName: "Section ID", enabled: true }, { Key: "room_l4", displayName: "Location", enabled: false }, { Key: "se ...

What is the best way to display the values from an array in a child component and pass them to the

How can I retrieve values from an array in the child component and display that data in the parent component? Initially, I was only displaying data from the array when the 'save' button was clicked. Now, I need to display the array by default. ...

Angular 2 - The creation of cyclic dependencies is not allowed

Utilizing a custom XHRBackend class to globally capture 401 errors, I have encountered a dependency chain issue in my code. The hierarchy is as follows: Http -> customXHRBackend -> AuthService -> Http. How can this problem be resolved? export class Custom ...

Unexpected output from nested loop implementation

Having some arrays, I am now trying to iterate through all tab names and exclude the values present in the exclusion list. json1 ={ "sku Brand": "abc", "strngth": "ALL", "area ...

Creating an HTTP method handler function in Next.js API routes with an unspecified number of generic parameters

Looking to create a wrapper function in NextJS for API routes that can handle multiple HTTP methods with different handlers. For example, check out the TS playground interface GetResponse { hello: string, } // empty object type PostResponse = Record&l ...

Tips for optimizing vendor.js and main.js files in Angular 15 using NX workspace

Looking to enhance the performance of my login page and overall application by reducing the size of vendro.js and main.js files. Tried setting optimization : true in project.json for my NX workspace project, but it didn't work as expected. Currently ...

The ViewChild property encountered an error: "The child element cannot be found"

I am facing an issue in Angular 7 where I have a parent component with a child component. I would like to obtain a reference to the child component within the parent component so that I can access its functions and properties. Child Component : @Componen ...

Incorporating quotes into a unified npm script

I'm trying to merge two npm scripts into one, but the result is incorrect and causes issues with passing flags. I can't use the dotenv package, and using ampersands isn't solving the problem. Here's what I have in my package.json file ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

Error encountered when packaging WebAssembly using Rollup

When I use wasm-pack to compile some rust code into webassembly, specifically with the option --target browser (which is the default), these are the files that I see in typescript/deps/ed25519xp: ed25519xp_bg.wasm ed25519xp_bg.d.ts ed25519xp.d.ts ed25519 ...

What is the best way to invoke a TypeScript function within a jQuery function?

Is it possible to invoke a TypeScript function within a jQuery function? If so, what is the correct approach? Here is an example of my component.ts file: getCalendar(){ calendarOptions:Object = { height: 'parent', fixedWeekCount : ...

Incorporate a personalized Cypress function for TypeScript implementation

I'm in the process of developing a custom cypress command that will enable me to post a file using formData, as the current cy.request does not yet support formData. For the actual POST operation, I am utilizing request-promise-native. To begin with ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Deploying an Angular application in a NodeJS environment using Azure DevOps

Can Azure DevOps Pipelines be used to automate the deployment of an Angular application to NodeJS or an on-premise WebServer? ...

How can you rearrange the order of objects in an array to only include duplicates?

I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an additional condition. var ...

Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push(). Every time I attempt this, I receive a console error stating: Uncaught (in promise) TypeError: ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...