Angular 2+ ActivationEnd事件回调多次调用

时间:2018-06-12 03:15:18

标签: angular angular-router

我看到一个router.events订阅会为每个路由更改回调函数产生三个调用,并且每个调用都会将instanceof event报告为ActivationEnd

console.log('This code runs only once, at site initialization.');
router.events.subscribe((event: RouterEvent) => {
    if (event instanceof ActivationEnd) {
        console.log('This should only log once per route change, but logs three times.');
    };
});

我在Github上发现了this thread,这看起来很相关,但我很难相信这仍然是一个问题......

我正在使用Angular 5(5.2.10)。

更新:看来此事件每个路段都会被触发一次......检查文档。

2 个答案:

答案 0 :(得分:2)

看来我应该使用NavigationEnd而不是ActivationEnd来实现所需的结果。我应该知道的。我想我的眼睛没有注意到差异。

答案 1 :(得分:0)

检查是否多次启动?

如果两次或多次执行此事件,

router.events.subscribe((event: RouterEvent) => {

然后它将被多次触发。

if (event instanceof ActivationEnd) {
    console.log('This should only log once per route change, but logs three times.');
};

所以请做到

    if (!alreadyexist){

    router.events.subscribe((event: RouterEvent) => {

      if (event instanceof ActivationEnd) {

        console.log('This should only log once per route change, but logs three times.');

      };
  });

}