I have a component that renders data based on the URL - '/lp/:pageId', :pageId is responsible for fetching data from the server called from ngOnInit()
.
ngOnInit(){
this.apiHelper.getData(this.route.snapshot.params.pageId);
}
I am facing an issue when ->
/lp/apple
=> this fetches data related to apple and renders properly/lp/apple
and press the link which navigates to /lp/banana
=> only the route changes but does not fetch any data as the component is already loaded.I tried calling the function to fetch data whenever the route changes, but that breaks some existing functionalities.
Any help regarding good Angular practice with this issue would be helpful. Thank you.
You can define your data reactively. Instead of fetching inside ngOnInit
, you can define a data observable that is dependent on the route param (since angular provides the route params as an observable on the active route):
public data$ = this.route.paramMap.pipe(
map(params => params.get('pageId')),
switchMap(pageId => this.apiHelper.getData(pageId))
);
constructor(private route: ActivatedRoute) { }
Here the data$
observable will emit the result of apiHelper.getData()
whenever the route param changes.