首页 文章

即使url未更改,Angular2 force组件也会在路由时重新加载

提问于
浏览
0

在我的页面上,有一个按钮,点击后根据用户的输入更改路由参数 .

Note: 此表单始终位于页面顶部

HTML:

<form [formGroup]="houseFrom">
    <input type="text" placeholder="ID" formControlName="id">
    <button (click)="openHouseDetails()">Go</button>
</form>

零件:

openHouseDetails(){
   const form = this.houseFrom.value;
   this.router.navigate(['chen/house',form.id]);
}

应用路由:

...
path:'chen',
children:[
   {path:'house/:id', component:HouseComponent}
   ...
]

在HouseComponent> ngOnInit方法中,使用随路由发送的参数调用某个服务 .

Now here is the issue:

如果用户插入id并单击该按钮,则URL将更改为ok并且HouseComponent已正确加载 .

BUT 如果用户现在再次单击按钮,具有相同的id,则URL不会更改(这很好),但由于这个原因,组件不会再次加载,因此不会再次调用ngOnInit .

这对我们来说不是预期的行为,因为在HouseComponent的ngOnInit中调用的服务可以在一段时间后返回不同的细节,因此每次单击按钮时它都应该再次调用该服务 .

即使URL未更改,如何强制组件重新加载?

2 回答

  • 0

    您可以在导航后调用您的服务:

    this.router.navigate(['chen/house',form.id])
      .then(() => this.callYourService());
    

    要么

    this.router.navigate(['chen/house',form.id])
      .then(() => this.ngOnInit());
    
  • -1

    试试 window.reload

    openHouseDetails(){
       const form = this.houseFrom.value;
       if(!this.router.url.includes(`chen/house/${form.id}`))//check if user is on current page
       this.router.navigate(['chen/house',form.id]);
       else
       location.reload()
    }
    

相关问题