角度:更改单个路线会发出多个“ NavigationEnd”事件

Mil*_*los 7 rxjs typescript angular angular-router

我正在使用Angular 4,这是我需要捕获该路由已更改并重新加载页面的组件之一中的代码。

ngOnInit() {
        this.router.events.subscribe((value) => {
          if (value instanceof NavigationEnd) {
             console.log(value);
          }
        });
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是我在一条路线上遇到多个“ NavigationEnd”事件。对于某些路由console.log,甚至可以写6,7个值。

那怎么可能发生?

Jot*_*edo 12

我认为“重载页面”是指调用的navigate方法this.router。如果真是这样,这很可能与以下事实有关:每次创建此组件的实例时,您都会为路由器事件创建一个新的观察者,但不要subscriptionngOnDestroy循环中处理生成的事件。要解决此问题,您可以执行以下操作:

import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/filter';    

export class FooComponent implements OnInit, OnDestroy {
   private _routerSub = Subscription.EMPTY;
   constructor(private router: Router){}

   ngOnInit(){
     this._routerSub = this.router.events
         .filter(event => event instanceof NavigationEnd)
         .do(event => console.log(value)) // use do operator for log operations
         .subscribe((value) => {
          //do something with the value
         });
   }

   ngOnDestroy(){
     this._routerSub.unsubscribe();
   }
}
Run Code Online (Sandbox Code Playgroud)