Angular:更改单个路由会发出多个 'NavigationEnd' 事件
Angular: changing single route emits multiple 'NavigationEnd' events
我正在使用 Angular 4,这是我在其中一个组件中的代码,我需要在其中捕获该路由已更改并重新加载页面。
ngOnInit() {
this.router.events.subscribe((value) => {
if (value instanceof NavigationEnd) {
console.log(value);
}
});
}
我的问题是一条路线收到多个 'NavigationEnd' 事件。
对于某些路线 console.log 甚至写入 6,7 个值。
怎么会这样?
我假设 "reload page" 是指调用 this.router
的 navigate
方法。如果是这样,这很可能与以下事实有关:每次创建该组件的实例时都会创建路由器事件的新观察者,但不要将生成的 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();
}
}
我正在使用 Angular 4,这是我在其中一个组件中的代码,我需要在其中捕获该路由已更改并重新加载页面。
ngOnInit() {
this.router.events.subscribe((value) => {
if (value instanceof NavigationEnd) {
console.log(value);
}
});
}
我的问题是一条路线收到多个 'NavigationEnd' 事件。 对于某些路线 console.log 甚至写入 6,7 个值。
怎么会这样?
我假设 "reload page" 是指调用 this.router
的 navigate
方法。如果是这样,这很可能与以下事实有关:每次创建该组件的实例时都会创建路由器事件的新观察者,但不要将生成的 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();
}
}