Struggling with Angular 2's Login Authentication - Caught in an Infinite Loop!

I am currently working on setting up User Authentication for a website backend using Angular 2. However, I have encountered some issues that I am struggling to resolve. Here is an overview of my approach.

Below is my routing file:

const appRoutes: Routes = [
 {
   path: 'admin',
   component: AdminloginComponent,
   canActivate: [LoggedInGuard]
 },
 {
   path: '',
   component: HomepageComponent
 },
 {
   path: '**',
   component: OurservicesComponent
 },
];

In the guard file, after a successful login, I set the "is_logged_in" flag in local storage:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class LoggedInGuard implements CanActivate {
 constructor(private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if(localStorage.getItem("is_logged_in"))
  {
      this.router.navigate(['/admin/dashboard']);
      return true;
  }
  return false;
}

*

My current issue arises when the URL is "/admin", triggering the canActivate method. If there is no data stored in the local storage indicating that the user is logged in, it redirects to "/admin/dashboard". However, I want to display a login form at "/admin" when the user is not logged in. Finding a solution to this problem is proving challenging. Any suggestions would be greatly appreciated.

Thank you in advance.

Answer №1

It's not entirely clear what your goal is, but when using router.navigate, the correct way to redirect is with return false;, not return true;

You can either use:

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(localStorage.getItem("is_logged_in")) {
      return true;
    }
    this.router.navigate(['/admin/dashboard']);
    return false;
  }

or

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if(localStorage.getItem("is_logged_in")) {
      this.router.navigate(['/admin/dashboard']);
      return false;
    }
    return true;
  }

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

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

Use lodash to filter out objects from an array that have a specific property

I'm dealing with a large array of objects and I need to retrieve the ones that have the property def defined, regardless of its value. Any help would be greatly appreciated. ...

What is the best way to selectively remove and then later reinsert two items from an array in

I am facing a scenario where I have two buttons and an array to work with. The buttons are labeled "OR" and "AND", and the array consists of 7 items in a Dropdown list. When the user clicks on the "OR" button, it should remove 2 items from the array. Co ...

Error message "Uncaught (in promise): Cannot locate module 'app/lazy/lazy.module'." encountered while attempting to lazy load using a factory

Applying the approach outlined in this response, I am implementing dynamic angular module loading as shown below: this.loader.load('app/lazy/lazy.module#LazyModule').then((moduleFactory: NgModuleFactory<any>) => { const entryC ...

Troubleshooting a problem with a callback function in Node.js

Recently, I have begun exploring API development in Node.js. In my Node.js application, I am utilizing JWT tokens for authentication purposes. The function responsible for validating JWT tokens is shown below: var jwt = require('jsonwebtoken'); ...

Modify the color of the chosen option in the dropdown menu without affecting the rest of the options

I am facing an issue with dynamic drop down lists in my HTML content. The requirement is to change the color of the selected option to dark red if the option is "success". I have implemented a jQuery function for this purpose. HTML: <select class="rea ...

The for loop unexpectedly interrupts a different array

Hey there, I've been working with puppeteer and came across an issue with the following code snippet: console.log(dealsId[i]); for (var i = 0; i < sizes.length; i++) { var refIdClasses = await sizes[i].$eval('input', a => a.getAtt ...

There seems to be an issue with ReactDOM.createPortal() generating redundant empty divs in next.js with TypeScript

This is the backdrop component in TypeScript: interface BacdropProps { open?: string; onClick: () => void; } const Backdrop: React.FC<BacdropProps> = (props) => { let container: HTMLDivElement | null = null; if (typeof window !== " ...

Design a customizable input field to collect HTML/JS tags

I'm looking to incorporate a similar design element on my website. Can anyone offer me some guidance? Check out the image here ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

What could be the reason why my listener is not functioning properly on a WordPress page?

I am encountering an issue with my code that listens for a click event on an anchor tag. It works perfectly when I have the code in a standalone HTML file. However, when I create a separate file for just the script, register and enqueue it, and then add ...

How to retrieve a specific item from an array in JavaScript

I am retrieving this list from the server using PHP: ["Ak-Bulak","Balykchy","Batken"] How can I access it and insert it into select options using JavaScript? Here is what I have tried so far: for (var i in data) { $('#cities').append(' ...

Bringing together Events and Promises in JS/Node is the key to seamless programming

I am exploring the most effective approach to incorporating events (such as Node's EventEmitter) and promises within a single system. The concept of decoupled components communicating loosely through a central event hub intrigues me. When one componen ...

Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, n ...

calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message Uncaught RangeError: Maximum call stack ...

Is the value of useState not updating even after setting it in a callback function?

I am facing an issue where the error message is not being added to the error state when an error occurs. The backend sends the error message in JSON format { "error": "error message" }, and even though I can log this error message successfully, the error ...

Tips for animating AngularStrap Collapse

My AngularStrap navbar collapse is functioning well, but the collapsing process lacks animation. Despite injecting the ngAnimate library and including the data-animation='am-collapse' attribute in my bs-collapse directive, I seem to have missed s ...

Exploring Angular: A guide to identifying toggle status in ng-bootstrap dropdown menus

Currently, I am utilizing these dropdown components. I am seeking a way to identify the status of the dropdown modal within either the template or ts file. Can you provide any guidance on this? ...

Guide to configuring the active Tab in Angular 6 using Angular Material Design

I've searched high and low for a solution to this issue, but I haven't been able to find one. In a particular component, I have a material tab control. However, the active tab doesn't display until I click on one of the tabs on the page. a ...

Exploring ways to extract specific information from a JSON file using Angular 2

Imagine we have a JSON file with 1000 records structured like the example below: [{ "name": "aaa", "age": 20 }, { "name": "bbb", "age": 21 }, ......] Is there a method to retrieve partial data from this JSON, such as the first 100 objects ...