Angular 4 Component ngOnInit not called on each route request

别等时光非礼了梦想. 提交于 2019-12-01 04:06:58

Angular prefers -by default- to reuse the same component instead of instanciating a new one if the route is the same but the parameters change.

Good news ! this is a customizable behavior, you can force instanciating a new component instance by implementing your own RouteReuseStrategy:

export class MyRouteReuseStrategy extends DefaultRouteReuseStrategy {
  shouldReuseRoute(next: ActivatedRouteSnapshot, current: ActivatedRouteSnapshot): boolean {
    let name = next.component && (next.component as any).name;
    return super.shouldReuseRoute(next, current) && name !== 'UserComponent';
  }
}

in your module:

@NgModule({
  ...
  providers:[{
      provide: RouteReuseStrategy,
      useClass: MyRouteReuseStrategy}]
  ...
})
export class AppModule {}

(this code is more or less taken from this article, especially the check for the name property which might not be very accurate...)

Note that ther might be some performance drawback when reinstanciating the same component. So maybe you'd better use the observables properties instead of the snapshot.

Michael

Does the url look like "...?id=1" or "../:id" and you want the component to log the id each time the GET param changes? The problem is talked about here. A better solution I found is here. I haven't tested it myself but this should work.

The second link shows how to subscribe to a route change within a component, which I think is essentially what you're trying to do. It will allow you to handle a GET param change within ngOnInit. I'm not sure if the route subscribe will run when you initally navigate to the URL, so you might want to have the function that handles the route event call a doCheck(), and change ngOnInit to ngAfterContentInit

ngOnInit only operates on change detection, and a GET change seems not to trigger it, which is surprising to me.

Tl;dr - Subscribe to the route change event in the constructor and create a function that handles an emitted event. The function should hold the logic you have in ngOnInit().

Hi you have to use switchMap like this:

this.sub = this.route.paramMap
  .switchMap((params: ParamMap) =>
  this.firebaseService.getProductsByCategory(params.get('category'))).subscribe(products => {
  this.products = products;
  this.count = products.length;
});

This work for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!