【问题标题】:Merging query params with @ngrx/router-store将查询参数与@ngrx/router-store 合并
【发布时间】:2018-03-06 07:28:20
【问题描述】:

我在我的 Angular 2+ 应用程序中使用 @ngrx/router-store 并尝试在 url 的查询参数中编码一些对象。具体来说,每次我在查询参数中编码一个对象时,我都想将它与已经存在的查询参数合并。为此,我根据the documentation 为路由器存储编写了以下副作用:

@Injectable()
export class RouterEffects {
  @Effect({ dispatch: false })
  navigate$ = this.actions$.pipe(
    ofType(RouterActions.GO),
    map((action: RouterActions.Go) => action.payload),
    tap(({ path, query: queryParams, extras}) => {
      this.router.navigate(path, { queryParams,  queryParamsHandling: "merge", ...extras }))
    })
}

然后要添加新的查询参数,我可以将它们分派到路由器存储:

store.dispatch(new RouterActions.Go({[], objectToEncode}));

这很好用,除非多个对象被快速连续分派,例如,当应用程序第一次加载时。在这种情况下,副作用将在前一个导航完成之前开始下一个导航,这意味着每个后续导航的查询参数将覆盖前一个导航的查询参数,因此只有最后一个对象将被编码到最终 url。

有没有办法防止副作用在上一个导航完成之前处理下一个 GO 操作? 我尝试使用商店中的查询参数压缩操作,但是当正在编码的对象已经在 url 中,防止 store 发出。

【问题讨论】:

  • 这个问题并不完全清楚。所以你有?first=1,然后是?second=2,你希望结果是?first=1&second=2。是对的吗?如果是这样,那么使用scan 运算符来聚合查询参数状态是否有意义?
  • 是的,您使用扫描操作员成功了。从Learn RxJS GitBook 中积累一个对象示例正是我所需要的。谢谢!

标签: angular typescript rxjs ngrx ngrx-effects


【解决方案1】:

正如@bygrace 所指出的,扫描操作符可以解决问题。这是修改为使用扫描运算符的原始代码:

@Injectable()
export class RouterEffects {
  @Effect({ dispatch: false })
  navigate$ = this.actions$.pipe(
    ofType(RouterActions.GO),
    map((action: RouterActions.Go) => action.payload),
    scan((currentRoute, {path, query: queryParams, extras}) => {
      const nextQueryParams = Object.assign({}, currentRoute.query, queryParams);
      return {path, query: nextQueryParams, extras};
    }, {path: [], query: {}, extras: {}}),
    tap(({ path, query: queryParams, extras}) => {
      this.router.navigate(path, { queryParams,  queryParamsHandling: "merge", ...extras }))
    })
}

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2017-11-03
    • 2017-01-31
    • 2018-09-18
    • 2018-01-30
    • 2018-03-30
    相关资源
    最近更新 更多