2017-01-16 92 views

回答

20

,你可以注入ActivatedRoute和訂閱params

constructor(route:ActivatedRoute) { 
    route.params.subscribe(val => { 
    // put the code from `ngOnInit` here 
    }); 
} 

路由器僅破壞並重新創建組件時,導航到不同的路線。當只更新路由參數或查詢參數但路由相同時,組件不會被銷燬和重新創建。

強制重新創建組件的另一種方法是使用自定義重用策略。又見Angular2 router 2.0.0 not reloading components when same url loaded with different parameters?(似乎沒有被太多的信息尚未提供如何實現它)創建一個實例時

+1

Thx,很好的解決方案。乾淨我想。 – AntiCZ

1

NgOnInit將被調用一次。對於相同的實例NgOnInit將不會再被調用。爲了調用它,有必要銷燬創建的實例。

0

考慮將您在ngOnInit中的代碼移動到ngAfterViewInit中。 後者似乎被稱爲路由器導航,並應在這種情況下幫助你。

+1

這確實沒有發生 – nadav

6

您可以在路由器上調整reuseStrategy。

constructor(private router: Router) { 
    // override the route reuse strategy 
    this.router.routeReuseStrategy.shouldReuseRoute = function() { 
     return false; 
    }; 
} 
相關問題