Issue
I normally use this way on routes with my apps.
ngOnInit() {
let id = this.route.snapshot.paramMap.get('id');
this.hero$ = this.service.getHero(id);
}
But above doc where I can see Observable based approach too.
ngOnInit() {
this.hero$ = this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')))
);
}
Can you tell me why do we need this approach? Doc says this
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
But it is not clear to me. Can you tell me why we need an Observable based approach?
Solution
you only get the initial value of the parameter map with this technique. Stick with the observable paramMap approach if there's even a chance that the router could re-use the component.
This means if there is a navigation event to the same component, Angular will not recreate the component since it is already available. Hence the ngOnInit won't be run again, resulting in ignoring the change in params(Snapshot only saves the first occurred value). In case of observables approach, it will be subscribed and change in params will be processed.
This use case should be considered, while you are displaying a entity like product and there is navigation button for relevant product.
Assume the url is "DOMAIN/product/1" and there is link for product 2. By clicking the link, the browser changes the url to "DOMAIN/product/2" but angular will reuse the product show component. The snapshot method will not notice the change due to above said reasons.
Answered By - Morsh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.