首页 文章

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

提问于
浏览
3

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

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

category 参数可以具有诸如“ free ", " top ", " paid ”之类的值,这些值使用导航栏进行路由 .

但我想添加另一个名为“ all " to be added to the nav-bar which should be the default when the app navigates to " /browse ”的类别值,在这种情况下 (I think) 我需要将一些数据(实际上是一个对象)传递给子路由(即“ /browse/all ”) . 子路由(基本上是子路由的组件)需要调用服务时需要此数据 .

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

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

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

2 回答

  • 1

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

    当您在应用程序中使用数据时,这是正确的 .

    但是如果你的数据来自外部,比如querystring,那么你应该把它保存到存储(通过调度一个动作),另一个组件应该从商店中获取这些数据 .

    只需角度你可以通过以下方式完成:https://angular.io/docs/ts/latest/cookbook/component-communication.html

    这并不意味着你不能使用这些数据绑定方式只考虑你有一个存储所有数据的存储 .

    在你的情况下

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

    我希望它有用 .

  • 0

    来自Victor Savkin的博文http://victorsavkin.com/post/145672529346/angular-router

    class TeamCmp {
      id: Observable<string>;
      constructor(r: ActivatedRoute) {
        //r.params is an observable
        this.id = r.params.map(r => r.id);
      }
    

相关问题