如何在Angular中检测路由变化?

21 浏览
0 Comments

如何在Angular中检测路由变化?

我想在我的AppComponent中检测路由变化。

之后,我将检查全局用户令牌,看看用户是否已登录,以便在用户未登录时重定向用户。

admin 更改状态以发布 2023年5月24日
0
0 Comments

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);
        });
    };
}

0
0 Comments

在Angular 2中,您可以通过一个Router实例订阅(Rx事件)。所以您可以做像以下这样的事情:

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以来)

请参见:Router.events文档

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

0