Angular 5: Route animations for navigating to the

2020-07-19 02:59发布

问题:

In my Angular 5 application, the user may navigate to a route which uses the same route, but with different parameters. For example, they may navigate from /page/1 to /page/2.

I want this navigation to trigger the routing animation, but it doesn't. How can I cause a router animation to happen between these two routes?

(I already understand that unlike most route changes, this navigation does not destroy and create a new PageComponent. It doesn't matter to me whether or not the solution changes this behavior.)

Here's a minimal app that reproduces my issue.

回答1:

This is an old question but that's it if you're still searching. Add this code to your app.Component.ts file.

import { Router, NavigationEnd } from '@angular/router';

constructor(private _Router: Router) { }

ngOnInit() {
  this._Router.routeReuseStrategy.shouldReuseRoute = function(){
  return false;
  };
  this._Router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
        this._Router.navigated = false;
        window.scrollTo(0, 0);
    }
  });
}

By using this code the page is going to refresh if you clicked on the same route no matter what is the parameter you added to the route.

I hope that helps.

Update

As angular 6 is released with core updates you don't need this punch of code anymore just add the following parameter to your routs import.

onSameUrlNavigation: 'reload'

This option value set to 'ignore' by default.

Example

@NgModule({
  imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload'})],
  exports: [RouterModule]
})

Stay up to date and happy coding.



回答2:

I ended up creating a custom RouteReuseStrategy which got the job done. It's heavily based on this answer.

export class CustomReuseStrategy implements RouteReuseStrategy {
  storedRouteHandles = new Map<string, DetachedRouteHandle>();

  shouldDetach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
    this.storedRouteHandles.set(route.routeConfig.path, handle);
  }

  shouldAttach(route: ActivatedRouteSnapshot): boolean {
    return false;
  }

  retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
    return this.storedRouteHandles.get(route.routeConfig.path);
  }

  // This is the important part! We reuse the route if
  // the route *and its params* are the same.
  shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
    return future.routeConfig === curr.routeConfig &&
      future.params.page === curr.params.page;
  }
}

Check it out on StackBlitz!