How would you protect a component being activated through the router?
How would you protect a component being activated through the router?
To protect a component from being activated through the router in Angular, you would use a route guard, specifically the CanActivate guard. The CanActivate guard is an interface that allows you to implement logic to determine whether a route can be activated or not. If the guard returns true, the navigation to the route will continue; if it returns false, the navigation will be cancelled.
Here's a step-by-step approach to implementing a CanActivate guard:
Create a Guard Service:
First, you need to create a service that implements the CanActivate interface. This service will contain the logic to determine whether the route should be activated.
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.