使用@ngrx/router-store 合并查询参数
Merging query params with @ngrx/router-store
我在我的 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 中时,这会失败,从而阻止商店发出。
正如@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 }))
})
}
我在我的 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 中时,这会失败,从而阻止商店发出。
正如@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 }))
})
}