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

What is Routing Guard in Angular?

Câu trả lời

Routing Guard in Angular is a feature used to control navigation within an Angular application, allowing developers to manage access to different routes based on specific conditions. These guards are essentially functions that determine whether a route can be activated, deactivated, or even loaded, based on the implementation of certain interfaces provided by Angular.

Types of Routing Guards

Angular provides several types of routing guards, each serving a distinct purpose:

  1. CanActivate: Determines if a user can activate a particular route. It's used to check if a user has the necessary permissions or meets certain criteria before accessing a route[1][3][4][8][9].
  2. CanActivateChild: Similar to CanActivate, but it applies to child routes. This guard checks if a user can access routes that are children of a specific route[3][7].
  3. CanDeactivate: Used to prevent navigation away from the current route under certain conditions, such as when there are unsaved changes on a form. It can ask users if they want to leave the page with unsaved changes[1][11].
  4. CanLoad: Controls whether a module can be lazily loaded. It is useful for feature modules that you want to load on demand, depending on certain permissions or conditions[3][9].
  5. Resolve: Used to perform route data retrieval before the route is activated. This guard ensures that necessary data is available before navigating to the desired route[1][3].

Implementation and Usage

Routing guards are implemented as services in Angular. A guard class implements one or more of the guard interfaces, such as CanActivate or CanDeactivate, and defines the logic within the respective methods like canActivate() or canDeactivate(). These methods typically return a boolean or an Observable/Promise that resolves to a boolean, indicating whether the route should be activated or not[1][3][8][9].

To use a routing guard, it is registered in the routing configuration of the Angular application. Here, you specify which routes should be protected by which guards. For example, you might protect a route using CanActivate to ensure that only authenticated users can access it[3][8][9].

Practical Example

Here's a basic example of how a CanActivate guard...



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


What is the difference between *ngIf vs [hidden] What is the difference between *ngIf vs [hidden] ??


What is the difference between Structural and Attribute directives in Angular?


What is Interpolation?

Bình luận

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

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