2017-10-09 304 views
0

我正在使用Angular 4,並且這是我在需要捕獲該路由已更改並重新加載頁面的組件之一中的代碼。Angular:更改單個路由發出多個'NavigationEnd'事件

ngOnInit() { 
     this.router.events.subscribe((value) => { 
      if (value instanceof NavigationEnd) { 
      console.log(value); 
      } 
     }); 
    } 

我的問題是,我得到一個路線的多個'NavigationEnd'事件。 對於某些路由console.log甚至寫入6,7個值。

這怎麼可能發生?

回答

1

我假設通過「重新加載頁面」,你的意思是調用navigate方法this.router。如果是這種情況,這很可能與您每次創建此組件的實例時創建路由器事件的新觀察者有關,但不要將生成的subscription置於ngOnDestroy週期中。要解決此問題,您可以執行以下操作:

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(); 
    } 
} 
+0

感謝您的迅速響應。這是我的問題,我沒有銷燬'ngOnDestroy'上的退訂事件。我不知道我應該這樣做:) – Milos

相關問題