已编辑
告诉路由器这样做的角度方式是使用onSameUrlNavigation从角度 5.1
但我必须以不同的方式(Stackblitz)解决这个问题,通过subscribing
调用route events
并实际调用custom reInit method
.
诀窍是将所有订阅添加到同一个对象,然后仅在 AngularngOnDestroy
调用时取消订阅,然后将模板变量的其余部分从custom destroy method
...
public subscribers: any = {};
constructor(private router: Router) {
/**
* This is important: Since this screen can be accessed from two menu options
* we need to tell angular to reload the component when this happens.
* It is important to filter the router events since router will emit many events,
* therefore calling reInitComponent many times wich we do not want.
*/
this.subscribers._router_subscription = this.router.events.filter(evt => evt instanceof NavigationEnd).subscribe((value) => {
this.reInitComponent();
});
}
reInitComponent() {
this.customOnDestroy();
this.customOnInit();
}
customOnInit() {
// add your subscriptions to subscribers.WHATEVERSUB here
// put your ngOnInit code here, and remove implementation and import
}
customOnDestroy() {
// here goes all logic to re initialize || modify the component vars
}
/**
* onDestroy will be called when router changes component, but not when changin parameters ;)
* it is importatn to unsubscribe here
*/
ngOnDestroy() {
for (let subscriberKey in this.subscribers) {
let subscriber = this.subscribers[subscriberKey];
if (subscriber instanceof Subscription) {
subscriber.unsubscribe();
}
}
}
请注意,如果您实现 lifecylce hook ngOnInit,您应该删除它并像示例中那样实现自定义方法。
unsubscription
由于这个角度错误,我添加了该方法。Angular 在销毁组件时实际上应该自动从 router.events 取消订阅,但由于情况并非如此,如果您不手动取消订阅,您最终会调用 http 请求(例如)与您进入组件一样多次。