Redirect to login not working in Angular auth guard

Seeking assistance with troubleshooting an issue within my app. I am attempting to implement a feature where, if the user is not logged in and tries to access any URL of the app, they should be redirected to the login page.

I have set up an auth guard, but it doesn't seem to redirect me or other users to www.my-domain.com/login. Instead, it remains on www.my-domain.com/dashboard while displaying a blank page...

What could be wrong in my code?

Below is the snippet from auth.service.ts:

login(): Observable<User> {
    const params = new HttpParams().append('param', 'value');
    return this.http.get<User>(`${environment.apiUrl}someurl` + location.search, {params}).pipe(
      tap((response: any) => {
        if (response && response.token) {
          localStorage.setItem('TOKEN_KEY', response.token);
          localStorage.setItem('username',response.user_name);
          localStorage.setItem('useremail',response.user_email);
          this.setAuthToken(response.token);
          this.isLoggedIn = true;
        } else {
          this.router.navigate(['/login']);
          return;
        }
      }),
      catchError(error => {
        console.error('Error:', error);
        return throwError(error);
      })
    );
  }

  isLogedIn() {
    const token = localStorage.getItem('TOKEN_KEY');
    return !!token;
  }

Next, the portion from auth.guard.ts:

export const authGuard = () => {
  const authService = inject(AuthenticationService);
  const router = inject(Router);

  if (authService.isLogedIn()) {
    return true;

  } else {
    console.log('Not logged in');
    return router.parseUrl('/login');
  }

};

Finally, referring to my app-routing.module.ts:

const routes: Routes = [
  { path: '',   redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent, title: 'Login', },
  {
    path: 'dashboard',
    component: DashboardComponent,
    title: 'Dashboard',
    canActivate: [authGuard],
    canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
  },
  {
    path: 'customers',
    component: CustomersComponent,
    title: 'Customers',
    canActivate: [authGuard],
    canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
  },
  {
    path: 'customers/customers/:id',
    component: CustomerComponent,
    title: 'Customer',
    canActivate: [authGuard],
    canMatch: [() => localStorage.getItem('TOKEN_KEY') != null]
  },

];

Where might the mistake lie? How could I have approached this differently?

Answer №1

In the auth.guard.ts file:

You can change it to the following code snippet:

else {
    console.log('User not logged in');
    return router.navigateByUrl('/login');
}

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

"The process of logging in to Facebook on Ionic app speeds up by bypassing

I'm facing a minor issue with Facebook login in Ionic. I've tried using Async - Await and various other methods to make it wait for the response, but nothing seems to work. The login function is working fine, but it's not pausing for me to p ...

Experiencing difficulties when utilizing Jest to test components

I recently started working with Jest and JavaScript. I wrote a test for one of my components, but it's failing, and I'm struggling to figure out what's wrong (seems like something related to enzyme). Here is the output: ● Console co ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

How can I color the first, second, and third buttons when the third button is clicked? And how can I color all the buttons when the fourth button is clicked?

I am trying to achieve a task with 4 buttons. When the third button is clicked, I want the first, second, and third buttons to change color. Similarly, when the fourth button is clicked, I want all buttons to change color. Additionally, I need to save a va ...

Tips for utilizing the Axios API client created using the OpenAPITools code generator

Currently, I am utilizing the Swagger/OpenAPI Codegen tool to automatically generate an API client for the Fetch client within my Vue application. However, I have decided that I would prefer to make use of Axios instead. To begin this transition, I initiat ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

Error: npm encountered a socket timeout issue

Setting up a fresh React application in /home/abhijith/Desktop/React/firstReact/myapp. Installing necessary packages. This process may require a few minutes. Installing react, react-dom, and react-scripts along with cra-template... npm ERR! code ERR_SOCK ...

add a hyperlink within a mouse click action

Looking for a way to make phone numbers clickable on mobile devices? Check out this script! I've implemented a script that displays a phone number when users click 'call us' and sends a Google Analytics event. However, I'm having troub ...

Implement user registration and authentication in your application using the powerful combination of React, Redux, and Express

I have a React and Redux application that utilizes Express and MongoDB. My goal is to allow users to register for an account, but I am struggling with how to make React/Redux send data to Express. In the long term, I want to store user account details such ...

I seem to be experiencing difficulty receiving the JavaScript alert on my controller page

In my ActionResult function, I have the following code: public ActionResult Copy( int bvVariableid ) { var iReturn = _bvRepository.CopyBenefitVariable( bvVariableid, CurrentHealthPlanId, CurrentControlPlanId, _bvRepository.GetSecInfo( ).UserId ...

JQuery GET brings back unnecessary HTML content

Currently utilizing a PHP cart class and implementing some jQuery to dynamically update a div when users add products. The issue I'm encountering is that upon adding a product, the list of products on the HTML page gets duplicated (see screenshot) ev ...

The $scope object in AngularJS has not been properly defined and

I am facing an issue with retrieving the value of email in my controller. It always returns 'undefined'. Here is my form: <form role="form" novalidate> <div class="form-group"> <input type="email" ng-model="user.emai ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

Decoding a JavaScript object when receiving it as JSON through a POST request

While browsing through various SO posts, I came across the statement "javascript is JSON". However, I am struggling to apply this concept in my application. My issue arises when I try to perform a POST request using jQuery. $.ajax({ type: &apo ...

Comprehending the intricacies of routing within AngularJS

Question: I've been looking into this issue, but there seems to be conflicting answers. I created a simple example in Plunker to understand how routers work in AngularJS, but I'm having trouble getting it to function properly... Below is my inde ...

Tips for transferring data between functions in component.ts in Angular 2

When I click a button, I am passing some values using "data.someid" and I want to retrieve this value in another button click. html --- <button (click)="click1(data.someid)"></button> <button (click)="click2()"></button> In my com ...

What causes a component to not update when it is connected to an Array using v-model?

Array1 https://i.stack.imgur.com/cY0XR.jpg Array are both connected to the same Array variable using v-model. However, when changes are made to Array1, Array2 does not update. Why is this happening? Process: Upon examining the logs, it can be observed th ...

What is the method for extracting user input from a text box on a webpage?

Having trouble with retrieving the value from a text box in my search function. SearchBar Component import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-search', templateUrl: './search.compon ...

Experiencing issues with effectively using a component

I have created a component, but I am unable to use it. This is a problem I have never faced before. https://i.sstatic.net/n5I8V.png Despite extensive Google searches, I have not been able to find a solution. For reference, you can view an example of the ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...