【问题标题】:Angular 5: Route animations for navigating to the same route, but different parametersAngular 5:用于导航到相同路线但参数不同的路线动画
【发布时间】:2018-06-12 17:11:08
【问题描述】:

在我的 Angular 5 应用程序中,用户可以导航到使用相同路由但参数不同的路由。例如,他们可能会从/page/1 导航到/page/2

我希望这个导航触发路由动画,但它没有。如何在这两条路由之间产生路由动画?

(我已经明白,与大多数路线更改不同,此导航不会破坏并创建新的PageComponent。解决方案是否更改此行为对我来说并不重要。)

Here's a minimal app that reproduces my issue.

【问题讨论】:

标签: angular5 angular-router angular-animations


【解决方案1】:

这是一个老问题,但如果您仍在搜索,就是这样。 将此代码添加到您的 app.Component.ts 文件中。

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);
    }
  });
}

通过使用此代码,如果您单击同一条路线,无论您添加到路线中的参数是什么,页面都会刷新。

希望对你有帮助。

更新

随着 Angular 6 的核心更新发布,您不再需要这些代码,只需将以下参数添加到您的 routs 导入中。

onSameUrlNavigation: 'reload'

此选项值默认设置为'ignore'

示例

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

保持最新状态并愉快地编码。

【讨论】:

  • 这是一个更老的回应!这个答案为我指明了正确的方向,我将发布我自己最终使用的内容。
  • 随着 Angular 6 的发布,我会发布更新。
  • 更新后的答案似乎是我最近切换到的角度 6 的更好解决方案。谢谢!
【解决方案2】:

我最终创建了一个自定义的RouteReuseStrategy,它完成了工作。它很大程度上基于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!

【讨论】:

  • (我在升级到 Angular 6 后使用了其他答案,但我将把这个留给 Angular 5 用户。)
猜你喜欢
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2019-06-21
  • 1970-01-01
  • 2016-12-02
  • 1970-01-01
相关资源
最近更新 更多