如何在 Angular 2 中找到前一条路由记录
如何在 Angular 2 中找到前一条路由记录
我想在我的AppComponent
中检测路由变化。
之后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向用户。
admin 更改状态以发布 2023年5月21日
RxJS 6
router.events.pipe(filter(event => event instanceof NavigationStart))
感谢 Peilonrayz(请参见下面的评论)
新路由> = RC.3
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router'; constructor(router:Router) { router.events.forEach((event) => { if(event instanceof NavigationStart) { } // NavigationEnd // NavigationCancel // NavigationError // RoutesRecognized }); }
您还可以按给定事件筛选:
import 'rxjs/add/operator/filter'; constructor(router:Router) { router.events .filter(event => event instanceof NavigationStart) .subscribe((event:NavigationStart) => { // You only receive NavigationStart events }); }
使用 pairwise
操作符获取先前和当前事件也是个好主意。https://github.com/angular/angular/issues/11268#issuecomment-244601977
import 'rxjs/add/operator/pairwise'; import { Router } from '@angular/router'; export class AppComponent { constructor(private router: Router) { this.router.events.pairwise().subscribe((event) => { console.log(event); }); }; }
在Angular 2中,您可以subscribe
(Rx事件)到一个Router实例中。因此,您可以做一些事情,例如
class MyClass { constructor(private router: Router) { router.subscribe((val) => /*whatever*/) } }
编辑(自rc.1以来)
class MyClass { constructor(private router: Router) { router.changes.subscribe((val) => /*whatever*/) } }
编辑2(自2.0.0以来)
另请参阅:routes.events文档
class MyClass { constructor(private router: Router) { router.events.subscribe((val) => { // see also console.log(val instanceof NavigationEnd) }); } }
。