Angular - Navigate to current same URL with component reload not the whole page

爷,独闯天下 提交于 2019-12-05 22:48:52

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 find 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 route 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:

https://medium.com/engineering-on-the-incline/reloading-current-route-on-click-angular-5-1a1bfc740ab2

In terms of rel-loading the entire page, the normal <a href="/">Reload Page</a> tag works just fine for me. I tried using the "onSameUrlNavigation" function, but it was not reloading the entire page the way I want.

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.

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