Câu hỏi phỏng vấn Angular
Câu hỏi

How would you protect a component being activated through the router?

Câu trả lời

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:

  1. 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.

    typescript Copy
    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');
      }
    }
  2. Register the Guard:
    After creating the guard, you need to provide it in your module's providers array.

    typescript Copy
    @NgModule({
      // ...
      providers: [AuthGuardService],
      // ...
    })
    export class AppModule { }
  3. 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.

    typescript Copy
    const routes: Routes = [
      {
        path: 'protected',
        component: ProtectedComponent,
        canActivate: [AuthGuardService]
      },
      // other routes...
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(rou...
junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What are the differences between AngularJS (angular 1.x) and Angular (Angular 2.x and beyond)?

expert

What is Locality principle for Ivy?

senior

What is Zone in Angular?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào