簡體   English   中英

當相同組件加載不同數據時,不會調用ngOnInit

[英]ngOnInit not called when same component is loaded with different data

我有一個有角度的2應用程序,我使用路由器在視圖之間導航,就像其他人一樣。 以下是我的特定組件的路徑:

{
    path: 'home/view1/:viewID',
    component: ViewComponent,
    children: [
        { path: 'pane/:paneId/section/:sectionId', component: SectionEditComponent },
        { path: '**', component: ViewEditComponent }
    ]
},

現在,我在ViewComponent上有兩個按鈕,為section1和section2加載SectionEditComponent。

路徑1:窗格/ 1 /部分/ 1
Path2:pane / 1 / section / 2

ViewComponent模板:

   <div class="col-md-8" style="background-color: white; height: 100%">
       <button (click)="loadPath(1)">Path1</button>
       <button (click)="loadPath(2)">Path2</button>
       <router-outlet></router-outlet>
   </div>

現在,當我從同一ViewComponent中的Path1-> Path2或Path2-> Path1導航時,不會調用ngOnInit(),因此不會加載新路徑,即使url實際上根據新的部分ID進行了更改。

這是已知的還是預期的行為? 有什么我做錯了嗎?

注入路徑並訂閱參數更改

constructor(route:ActivatedRoute) {
  route.params.forEach(params => {
    myInit(params['paramId']);
  });
}

只是想補充一點,如果您在組件加載之前使用路由解析器來獲取數據,那么您可以將以下代碼放在組件的ngOnInit方法中:

ngOnInit(){
    this.activatedRoute.data.subscribe(data => {
         initData(data['mydata']);
    });
}

initData(data){
    // process new data
}

現在,只要解析器更新路徑的已解析數據,組件的模型就會更新並顯示新數據。

對於組件的同一實例, ngOnInit()僅被調用一次。

我有一個類似的問題,ngOnInit沒有被路由更改調用。 我將代碼移動到ngAfterViewInit()並且它工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM