Angular - Navigate to current same URL with component reload not the whole page
If I understand you correctly, this is how I do it:
ngOnInit(): void { this.route.params.subscribe( params => { const id = +params['id']; this.getMovie(id); } );}
Or to watch query parameters:
ngOnInit(): void { this.route.queryParams.subscribe(param => { this.pageTitle = 'Movie List'; this.getMovies(); });}
In the ngOnInit, I watch for changes to the parameters. When the parameters change, I re-retrieve the data.
Since the data is all bound, the page "refreshes" with the newly retrieved data.
I have found this workaround method since the onSameUrlNavigation
property in Angular 5.1 is not what I need.
I just need to override shouldReuseRoute
, so added an exception for the component route that I want to refresh, if the current and future route are equal view
.
And also I can navigate to other routes without problems, even for navigate from Angular Material
sidenav
.
this.router.routeReuseStrategy.shouldReuseRoute = function (future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot) { if (future.url.toString() === 'view' && curr.url.toString() === future.url.toString()) { return false; } return (future.routeConfig === curr.routeConfig);};
Update:
For those they want to use the new onSameUrlNavigation
property in Angular 5.1 you can refer to this blog:
In route module: add below in each route declaration
runGuardsAndResolvers: 'always'
and
@ngModule({ imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: ‘reload’})], exports: [RouterModule], })
for e.g category/:id
and this below part will be under Component
ngOnInit() { this.activeRoute.queryParams.subscribe(queryParams => { // do something with the query params }); this.activeRoute.params.subscribe(routeParams => { this.loadUserDetail(routeParams.id); });}
for each route change say for e.g category/11
and category/12
it will call loadUserDetail
function everytime.
So without refreshing page you will fetch data from server and update dom for same route with different roureParams.