我要听NavigationStart事件,并判断其url
属性是/logout
。如果是这样,路由器应该停止射击连续事件,如RoutesRecognized,GuardsCheckStart,ChildActivationStart等,当我的侦听器检测到正确的NavigationStart事件。否则,路由器应该继续路由。
我不想用一个组成部分,因为我是不会显示任何/logout
视图。
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
}
}
您可以使用路由后卫。当路由匹配“注销”,在“YourGuard”将被用于激活与否的路线。如果警卫返回true,它会被重定向到“用户/ sign_in”(只是一个例子)。如果不是,YourGuard里面你可以重定向到其他路径或做其他事。
{ path: 'logout', canActivate: [ YourGuard ], redirectTo: 'users/sign_in' }
你并不需要“听”到路由事件。了解更多关于警卫here。