angular - 如何在ngrx Angular2中将数据从父路由传递到子路由

标签 angular angular2-routing ngrx

我正在使用@ngrx 路由器,其中一个路由有一些子路由器(基本上传递路由参数),如下所示:

{
path: '/browse',
component: BrowseComponent,
children: [
  {
    path: ':category',
    component: CategoryComponent
  }
]
}

category 参数可以有“free”、“top”、“paid”等值,它们被路由到使用导航栏。

但我想添加另一个名为“all”的类别值添加到导航栏,当应用导航到“/browse”时,这应该是默认值"在这种情况下,(我认为) 我需要将一些数据(实际上是一个对象)传递给子路由(即“/browse/all”)。该数据在子路由(本质上是子路由的组件)需要调用服务时需要。

我尝试使用 index 路由,将 CategoryComponent 设置为“/browse”的 index,如下所示

{
path: '/browse',
component: BrowseComponent,
index: {
  component: CategoryComponent
},
children: [
  {
    path: ':path',
    component: CategoryComponent
  }
]
}

但我仍然不确定如何将数据从 BrowseComponent 传递到 CategoryComponent。关于如何将数据从父路由组件传递到子路由组件的任何想法?还是我做错了,可以使用其他一些更好的方法在子路由中添加 all 类别。 谢谢

最佳答案

首先,当您使用 ngrx 时,您需要将您的 Store 视为“单一事实来源”。这意味着每次获取数据时,您都应该从商店中检索它。

当您在应用程序中处理数据时,这是正确的。

但是如果你的数据来自外部,比如查询字符串,那么你应该将它保存到存储中(通过调度一个 Action ) 另一个组件应该从商店中获取这些数据。

在 Angular 上,您可以通过以下方式完成:https://angular.io/docs/ts/latest/cookbook/component-communication.html

这并不意味着您不能使用这些数据绑定(bind)方式,只要考虑您有一个存储所有数据的商店即可。

在你的情况下

  constructor(private store: Store<fromRoot.State>, route: ActivatedRoute) {
    this.actionsSubscription = route.params
      .select<string>('path')
      .map(path => new action.SomeAction(path))
      .subscribe(store);
  }

希望对您有所帮助。

关于angular - 如何在ngrx Angular2中将数据从父路由传递到子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37796352/

相关文章:

Angular 2 : Where is url 'api/heroes' defined?

Angular2 - 使用服务的组件之间的交互

angular - 带滤镜的 ngrx 效果有效吗?

Angular/w ngrx - 连续 API 调用

javascript - 如何在完成两个 Angular 2 订阅后调用一个函数?

angular - 即使 OnPush 策略开启,什么事件也会触发变更检测?

javascript - 如何避免 Angular 中的元素重叠

javascript - 在 ng2 中实现下拉菜单的正确方法?

javascript - 如何更正 NodeJS 找不到已安装的包?

angular - 使用 ActionReducerMap : "not assignable to type ' ActionReducerMap<AppState, Action> 注册 reducer 时出错