如果使用url地址栏操纵路径,则不会调用Angular 2,Constructor和ngOnInit

时间:2018-03-21 13:31:34

标签: angular angular2-routing

我正在访问某些路线,例如:http://xyz.domain.com/profile/1。现在,当我使用参数2(即http://xyz.domain.com/profile/2)操作相同的URL时,与此路由关联的组件未被激活,而OnInit未被调用。有没有人知道为什么这种行为?任何人都可以帮忙吗

2 个答案:

答案 0 :(得分:1)

它不起作用,因为您的组件未被销毁。如果你保持相同的路线,那么你既不会破坏你的组件,也不会重新创建它。

如果您想查看此行为的示例,请feel free to look at this stackblitz

如果您想在同一个网址导航中制作内容,则必须收听路由事件,并在结束时执行某些操作。这样的事情。

this.router.events.subscribe(event => {
  if (!(event instanceof NavigationEnd)) { return; }
  this.ngOnInit();
});

答案 1 :(得分:-1)

希望这可以帮助任何人根据@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();
    }
  }
相关问题