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

How to detect a rout...

Câu trả lời

To detect a route change in Angular, you can subscribe to the router events observable provided by the Angular Router. This observable emits navigation-related events, including start and end of navigation, route recognition, and errors. Here's a step-by-step guide on how to implement route change detection:

  1. Import the Router and Event Types: First, you need to import Router and the event types you want to listen for from @angular/router. The event types include NavigationStart, NavigationEnd, NavigationCancel, NavigationError, and others.

    import { Router, Event, NavigationStart, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';
  2. Subscribe to Router Events: Inject the Router into your component's constructor and subscribe to its events observable. You can then filter the events based on their instance type to detect specific navigation events.

    constructor(private router: Router) {
        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
                // Navigation is starting
                console.log('Route change detected');
            } else if (event instanceof NavigationEnd) {
                // Navigation End
                console.log(event);
            } else if (event instanceof NavigationCancel) {
                // Navigation Cancel
                console.log('NavigationCancel ', event.url);
            } else if (event instanceof NavigationError) {
                // Navigation Error
                console.log(event.error);
            }
        });
    }
  3. Handle Route Change Logic: Inside the subscription, you can implement the logic you want to execute on route changes. For example, you might want to show a loading indicator when navigation starts and hide it when navigation ends.

  4. Unsubscribe to Prevent Memory Leaks: It's important to unsubscribe from the router events when the component is destroyed to prevent memory leaks. This can be done by implementing the OnDestroy lifecycle hook and using a subscription object to keep track of the subscription.

    import { Subscription } from 'rxjs';
    
    export class MyComponent implements OnDestroy {
        private subscription: Subscription;
    
        constructor(private router: Router) {
            this.subscription = this.router.events....
senior

senior

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

senior

What does detectChanges do in Angular Jasmine tests?

middle

What is Redux and how does it relate to an Angular app?

expert

Angular 9: Explain improvements in Tree-Shaking

Bình luận

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

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