告诉路由器这样做的角度方式是使用角度 5.1 的onSameUrlNavigation ......但我认为实现这一点仍然存在一些问题。
所以我不得不以不同的方式(Stackblitz)解决这个问题,通过subscribing
调用route events
并实际调用custom reInit method
.
诀窍是将所有订阅添加到同一个对象,然后仅在ngOnDestroy
被 angular 调用时取消订阅,并且将模板变量的其余部分从custom destroy method
...那么@Yazan Mehrez 的回答应该可以,但是如果您确实有订阅或使用钩子,那么您需要一个像下面这样的实现来防止内存泄漏:
public subscribers: any = {};
constructor(private router: Router) {
/**
* This is important: Since this screen can be accessed from two menu options or has query string parameter changes
* 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 请求(例如)与您进入组件一样多次。