Angular 2,如果使用 url 地址栏操作路由,则不会调用构造函数和 ngOnInit
Angular 2, Constructor and ngOnInit not getting called if route is manipulated using url address bar
我正在访问某个路由,例如:http://xyz.domain.com/profile/1. Now when i manipulate the same url with parameter 2 i.e http://xyz.domain.com/profile/2,与此路由关联的组件未被激活,即未调用 OnInit。有谁知道为什么会出现这种行为?谁能帮忙解决这个问题
它不起作用,因为你的组件没有被破坏。如果你留在同一条路线上,那么你既不会破坏你的组件,也不会重新创建它。
如果您想查看此行为的示例,feel free to look at this stackblitz。
如果你想在同一个 URL 导航上做一些事情,你将不得不监听路由事件,并在它结束时做一些事情。像这样。
this.router.events.subscribe(event => {
if (!(event instanceof NavigationEnd)) { return; }
this.ngOnInit();
});
希望这对@trichetriche 评论中的任何人有所帮助
// ... your class variables here
navigationSubscription;
this.navigationSubscription = this.router.events.subscribe(event => {
if (!(event instanceof NavigationEnd)) { return; }
this.ngOnInit();
});
现在在 ngDestroy 上我们需要取消订阅它,否则即使在正常导航的情况下,后续路由器事件也会为每个路由实例调用 ngOnInit()。
ngOnDestroy() {
// method on every navigationEnd event.
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}
我正在访问某个路由,例如:http://xyz.domain.com/profile/1. Now when i manipulate the same url with parameter 2 i.e http://xyz.domain.com/profile/2,与此路由关联的组件未被激活,即未调用 OnInit。有谁知道为什么会出现这种行为?谁能帮忙解决这个问题
它不起作用,因为你的组件没有被破坏。如果你留在同一条路线上,那么你既不会破坏你的组件,也不会重新创建它。
如果您想查看此行为的示例,feel free to look at this stackblitz。
如果你想在同一个 URL 导航上做一些事情,你将不得不监听路由事件,并在它结束时做一些事情。像这样。
this.router.events.subscribe(event => {
if (!(event instanceof NavigationEnd)) { return; }
this.ngOnInit();
});
希望这对@trichetriche 评论中的任何人有所帮助
// ... your class variables here
navigationSubscription;
this.navigationSubscription = this.router.events.subscribe(event => {
if (!(event instanceof NavigationEnd)) { return; }
this.ngOnInit();
});
现在在 ngDestroy 上我们需要取消订阅它,否则即使在正常导航的情况下,后续路由器事件也会为每个路由实例调用 ngOnInit()。
ngOnDestroy() {
// method on every navigationEnd event.
if (this.navigationSubscription) {
this.navigationSubscription.unsubscribe();
}
}