Navigating deprecated CanActivate in Angular-15 with Auth Guard

Authentication Guard:

import { Injectable, inject } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateFn, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private route:Router){}
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if(localStorage.getItem('userdata')){
      return true;
    }else{
      this.route.navigate(['login'])
      return false;
    }
  }
}  

I encountered an error stating that

'CanActivate' is deprecated.ts(6385)
index.d.ts(302, 4): The declaration was marked as deprecated here.

How can I resolve this issue? I aim to restrict access to a dashboard without a successful login and redirect users back to the login page.

Answer №1

Angular offers a standalone API called CanActivateFn instead of the traditional method:

For more information, refer to this guide: https://angular.io/api/router/CanActivateFn

Here is a sample scenario:

export const authGuard: CanActivateFn = (
  route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot,
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree => {
  const router = inject(Router);
  if (localStorage.getItem('userdata')) {
    return true;
  } else {
    return router.navigate(['login']);
    /** no need to return 'false', just return the promise */
  }
};

Alternatively:

export const authGuard: CanActivateFn = () => {
  return !!localStorage.getItem('userdata') || inject(Router).navigate(['login']);
};

For example:

@Injectable()
class UserToken {
}

@Injectable()
class PermissionsService {
  canActivate(currentUser: UserToken, userId: string): boolean {
    return true;
  }
  canMatch(currentUser: UserToken): boolean {
    return true;
  }
}

const canActivateTeam: CanActivateFn =
    (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
      return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']);
};

Define a route as follows:

{
      path: 'team/:id',
      component: TeamComponent,
      canActivate: [canActivateTeam],
}

Answer №2

If you're looking to restrict access, you can utilize the canActivateFn function!

import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';

const AuthGuard: CanActivateFn = () => {
     const route = inject(Router);
     if(localStorage.getItem('userdata')){
         return true;
     }else{
         route.navigate(['login'])
         return false;
     }
};

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

Passing a single item from a list as a prop in Vue.js

Imagine having the following set of information in data: data: { todos: [ { id: 1, title: "Learn Python" }, { id: 2, title: "Learn JS" }, { id: 3, title: "Create WebApp" } ] } Now, I aim to send only the item with an id of 2 t ...

adjust back side height of flip box does not function on IE web browser

I'm currently working on flipping a div/box, and while it's functioning correctly, I'm facing an issue with the height of the back side exceeding that of the front side. This causes the flipped div to always push down to the next element (e. ...

Submitting forms using Ajax within a modal pop-up box

Here's an interesting issue that I'm facing: On a test page, when the user clicks to view results, a modal box opens with 3 select boxes. Select Box 1 populates Select Box 2, which then populates Select Box 3 The Problem: After clicking submi ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

One question I have is how I can successfully send a value within the RxJS subscribe function

I am currently in the process of transitioning the code to rxjs Here is my original code snippet. userAuth$: BehaviorSubject<ArticleInfoRes>; async loadArticleList(articleId: number) { try { const data = await this.articleApi.loadArticl ...

Importing named exports dynamically in Next.js

Currently, I am in the process of learning Next.js and I want to utilize a function called getItem from the package found at https://www.npmjs.com/package/encrypt-storage In my attempt to do so using the code snippet below, I encountered an error stating ...

Narrow down your search results with date range filtering in Angular Material

Seeking guidance as a newcomer to Angular Material, I am trying to implement a date range filter for a table of N results. The options in the filter select are (1 day, 5 days, 1 week, 15 days), which are populated using a variable JS vm.rangos=[ {id ...

Is there a way to make the fixed table header scroll along with the table body data?

I am facing an issue with my table where I have multiple columns. I have managed to fix the table header successfully, however, when I scroll horizontally through the table body columns, the header remains fixed and does not move accordingly. How can I res ...

I'm fascinated by the way well-known websites like The Guardian are utilizing Angular, as I often notice that when I click on links, the entire page reloads

As a beginner in Angular, I recently explored popular websites that implement Angular or React. I discovered sites like The Guardian, New York Times, and Netflix. However, most of these sites have links that open in new pages, while the remaining ones ut ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Changing the element tag and flipping escape characters in html entities

My control over the string source is limited, as I can only use html(). However, I am in need of cleaning up the chaos within the source, The goal is to remove all instances of <div class="page"></div>, while retaining its content. The challen ...

Most effective method to verify if mutation observer meets specific criteria

I have set up a mutation observer to monitor changes in the page load. Specifically, I am interested in detecting the moment when a particular element is loaded or exists. This element can be identified by its classname, let's say it's called foo ...

How can I switch out an item within FabricJS?

In order to incorporate undo and redo functionality, I have created an array named "history" that stores the most recent changes triggered by canvas.on() events. Displaying console.log: History: (3) […] ​ 0: Object { target: {…} } //initial object ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Injecting dynamic content using JavaScript

My goal is to develop a web page where clicking on any of the three images will cause the content to be inserted into the empty div located above the image links. Below is the JavaScript code I'm using: <script type="text/javascript" src="js/jque ...

Display content from Angular 5 template directly in table without using parent template

Despite the fact that this question has been raised multiple times, I find myself in a slightly tricky situation. Here is the structure of my table: <table> <th>...</th> <app-custom-rows *ngFor="let t..." [customAttribute]="someval ...

Having difficulty utilizing defineProps in TypeScript

For some time now, I've been utilizing withDefaults and defineProps. Unfortunately, this setup has recently started failing, leaving me puzzled as to why! Here's a simple SFC example: <script setup lang = "ts"> const props ...

Values are being set back to '1' within the popup dialog

After recently incorporating Twitter Bootstrap into my web app project, everything seemed to be going smoothly until I encountered an issue with a modal window. Following the Bootstrap documentation, I set up a button that triggers a modal window to appea ...

Retrieve the value from another select element

Is there a way to create a function in pure JavaScript that changes the selected options in two select tags based on each other? For example, if I choose a French word in one select tag, the English equivalent automatically changes in the other select tag ...