NgRx-无法从CustomSerializer路由器存储访问多级路由参数

时间:2018-09-07 08:35:07

标签: angular redux ngrx ngrx-router-store

我有一条声明为的路径:

{
  path: 'app/:userId',
  children: [...AppChildrenRoutes]
}

然后在AppChildrenRoutes内部

{ path: 'feature', component: MainFeatureComponent }

因此,在我的应用程序中,我可以拥有localhost:4200/app/123/feature。 在此组件内,通过执行一些操作,我可以导航到另一条这样的路线:

this.router.navigate([
  'app',
  this.userId,
  'feature',
  { search: this.searchFor }
]);


逐步将其视为正在改变架构的大型企业规模应用程序,以使用NgRx。
因此,我遇到了路由器存储的问题。我已经设置好了,一切都正常。
在路由器存储docs之后,我写了一个自定义序列化器,它看起来像这样

serialize(routerState: RouterStateSnapshot): RouterStateUrl {
  const { url } = routerState;
  const queryParams = routerState.root.queryParams;

  while (route.firstChild) {
    route = route.firstChild;
  }
  const params = route.params;

  return { url, queryParams, params };
}

我发现,考虑使用URI之类的

localhost:4200/app/123/feature;search=blue

route.params仅返回search参数,而不同时返回userIdsearch

-如何实现从路径返回所有CustomSerializer的{​​{1}}? (在这种情况下,paramsuserId)。

我有点尝试过,但是没有成功,在while循环的每次迭代中,检查是否有参数并将它们添加到一个对象中直到最后一个。好的,好的还是不好的方法?我该如何工作而不会失败?
谢谢。

2 个答案:

答案 0 :(得分:2)

我遇到了类似的问题,并在每次循环时都通过扩展params对象来解决。

我的CustomSerializer现在看起来像这样:

override fun onDestroyView() {
    super.onDestroyView()
 myRelativeLayout.viewTreeObserver.removeOnGlobalLayoutListener(myLayout)
}

}

答案 1 :(得分:0)

您可以使用选择器选择任何父/子路由,并且不需要序列化程序。您具有根Route的对象,并通过创建选择器可以遍历路由并获取所需的参数。

const selectRouter = createFeatureSelector<XStore,
    fromRouter.RouterReducerState<any>>('router');

export const selectAllRouteParam = (param: string) => createSelector(
    selectRouter,
    (router: RouterReducerState) => {
        let current = router.state.root;

        while (current) {
            if (current.params && current.params[param]) {
                return current.params[param];
            } else {
                current = current.firstChild;
            }
        }
    }
);

使用时,您可以像这样使用它:

userId$ = this.store.select(selectAllRouteParam('userId'))

晚了聚会,但我希望将来有人会对此有所帮助。

相关问题