代码之家  ›  专栏  ›  技术社区  ›  João Ghignatti

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

  •  0
  • João Ghignatti  · 技术社区  · 6 年前

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

    我发现,考虑到

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

    route.params 仅返回 search param,不是两个都是 userId .

    -如何实现 CustomSerializer params 从小路上?(在这种情况下,两者 ).


    谢谢。

    1 回复  |  直到 6 年前
        1
  •  5
  •   coettl    6 年前

    我遇到了一个类似的问题,每次遍历循环时都通过扩展params对象来解决它。

    我的CustomSerializer现在如下所示:

    export class CustomSerializer implements RouterStateSerializer<RouterStateUrl> {
    serialize(routerState: RouterStateSnapshot): RouterStateUrl {
        let route = routerState.root;
    
        let params = {};
        while (route.firstChild) {
            params = {
                ...params,
                ...route.params
            };
            route = route.firstChild;
        }
    
        const {
            url,
            root: { queryParams }
        } = routerState;
    
        return { url, params, queryParams };
    }
    

    }

        2
  •  0
  •   SureshS    5 年前

    您可以使用选择器选择任何父/子路由,而不需要序列化程序。您有一个根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'))