【问题标题】:Angular 2 Router: Add RouteParam without re-creating the componentAngular 2 路由器:添加 RouteParam 而不重新创建组件
【发布时间】:2016-07-18 00:23:45
【问题描述】:

我有以下模板:

<aside class="fv-right-sidebar" *ngIf="_routeParams.get('sidebar')">
  <fv-account *ngIf="_routeParams.get('sidebar') === 'account'" [accountId]="_routeParams.get('accountId')" (canceled)="closeSidebar()" (saved)="closeSidebar()"></fv-account>
  <fv-transaction *ngIf="_routeParams.get('sidebar') === 'transaction'" [transactionId]="_routeParams.get('id')" (canceled)="closeSidebar()" (saved)="closeSidebar()"></fv-transaction>
</aside>

例如添加帐户时,我会使用this._router.navigate(['/Dashboard', {sidebar: 'account'}])。但是,整个仪表板组件会重新构建。我正在寻找一种无需重新加载父组件即可设置查询参数的方法。我尝试按照here 的建议使用location.go。它确实会更新 url,但不会更新 RouteParams。我正在寻找一种无需重新加载组件即可设置路由参数的方法。如果这(已经)可行,有什么想法吗?

建议here 使用子路由。但是,由于侧边栏并不总是显示,而且我不确定如何处理输入(accountId、transactionId)而不必将组件重写为 routeparams,我想知道是否有更简单的方法来更新 RouteParams。

谢谢, 罗宾

解决方案

正如@günter-zöchbauer 建议的那样,解决方案是使用CanReuseOnReuse

  routerCanReuse(nextInstruction:ComponentInstruction, prevInstruction:ComponentInstruction):any {
    return true;
  }

  routerOnReuse(nextInstruction:ComponentInstruction, prevInstruction:ComponentInstruction):any {
    this._routeParams = new RouteParams(nextInstruction.params);
  }

【问题讨论】:

    标签: angular


    【解决方案1】:

    实现CanReuse并返回true

    class MyCmp implements CanReuse {
      routerCanReuse(next: ComponentInstruction, prev: ComponentInstruction) { return true; }
    }
    

    另请参阅有关 CanReuse 何时有效以及何时无效 https://github.com/angular/angular/issues/7784 的讨论

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2017-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-20
      相关资源
      最近更新 更多