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
): Observable<boolean> | Promise<boolean> | boolean {
// Your authentication logic here
if (this.isLoggedIn()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
private isLoggedIn(): boolean {
// Implement check for login status
return !!localStorage.getItem('userToken');
}
}
Register the Guard:
After creating the guard, you need to provide it in your module's providers array.
@NgModule({
// ...
providers: [AuthGuardService],
// ...
})
export class AppModule { }
Protect the Route:
In your routing configuration, you can now protect your route by adding the canActivate
property and assigning the guard service to it.
const routes: Routes = [
{
path: 'protected',
component: ProtectedComponent,
canActivate: [AuthGuardService]
},
// other routes...
];
@NgModule({
imports: [RouterModule.forRoot(rou...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào