How to detect a rout...
How to detect a rout...
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:
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';
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);
}
});
}
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.
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào