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

Angular 2+ ActivationEnd event callback called multiple times

我看到一个订阅 router.events 每次路由更改都会产生三个调用回调函数,每个报告 instanceof eventActivationEnd

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)。

更新:似乎每个路线段都会触发一次此事件...正在检查文档。

看来我应该使用 NavigationEnd 而不是 ActivationEnd 来达到预期的结果。我早该知道的。我想我的眼睛没有注意到差异。

检查是否多次启动?

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

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.');

      };
  });

}

你可以使用distinctUntilChanged来解决这个问题。仅在 URL 不同时触发。

let prevUrl = ''
this.router.events.pipe(
    filter((e) => e instanceof ActivationEnd),
    distinctUntilChanged((prev, curr) => this.router.url === prevUrl),
    tap(()=>prevUrl = this.router.url),
).subscribe((event: RouterEvent) => {
        console.log('This should only log once per route change, if url is the same ');    
});