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.

    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.

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

    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

middle

How do you perform Error Handling for HttpClient ?

senior

How to detect a route change in Angular?

senior

What does detectChanges do in Angular Jasmine tests?

Bình luận

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

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