I want to listen to NavigationStart event and judge if its url attribute is /logout.
If so, the router should stop firing successive events, such as RoutesRecognized, GuardsCheckStart, ChildActivationStart, etc., when my listener detects correct NavigationStart event.
Otherwise the router should keep on routing.
I don't want to use a component, 'cause I ain't gonna display any /logout view.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
constructor(
private router: Router,
) {
router.events.filter(event => event instanceof NavigationStart).subscribe(
(event: NavigationStart) => {
if (event.url == '/logout') {
this.logout();
// TODO stop firing successive events
}
}
);
}
ngOnInit() { }
logout() {
// TODO logout operations
}
}
You can use a route guard. When route matches 'logout', the 'YourGuard' will be used to activate or not the route. If the guards returns true, it will be redirected to 'users/sign_in' (just an example). If not, inside the YourGuard you can redirect to other path or do something else.
{ path: 'logout', canActivate: [ YourGuard ], redirectTo: 'users/sign_in' }
You don't need to 'listen' to the route events. Read more about guards here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With