在 ngrx 效果中基于 ID 遍历对象数组
Looping through an array of object based on ID in ngrx effects
我想遍历存在于对象数组中的 ID,然后将其传递给另一个操作。我试过 data.foreach 但出现错误。很可能我没有使用正确的 RXjs 运算符。在这方面的任何帮助将不胜感激。
示例数据= [{id:1, 姓名: 'name1'}, {id:2, 姓名: 'name1'}]
loadSucces$ = createEffect(() =>
this.actions$.pipe(
ofType(Actions.loadSuccess),
switchMap(([data]) =>
// data returns an array of objects, from whose id I want to go through
this.service
.get('data.id')
.pipe(
map(serviceData =>
Actions.loadDataSuccess({ serviceData })
),
catchError(error =>
of(Actions.loadDataSuccess({ error }))
)
)
)
)
);
创建您要执行的操作的数组,然后使用 from
在其上调用 mergeMap
。
// ....
mergeMap(([data]) => {
const actions = data.map(item => Actions.someAction(item));
// now actions is an array of actions we want to pass further.
return from(actions);
})
那么每一项操作都将通过商店进行处理。
https://timdeschryver.dev/snippets/multiple-service-calls-from-an-effect
refresh$ = createEffect(() =>
this.actions$.pipe(
ofType(CustomerActions.refresh),
exhaustMap(({ customerIds }) =>
merge(
...ids.map(id =>
this.customersService.getCustomer(id).pipe(
map(CustomerActions.getCustomerSuccess),
catchError(err =>
of(CustomerActions.getCustomerFailed(id, err.message)),
),
),
),
),
),
),
)
我想遍历存在于对象数组中的 ID,然后将其传递给另一个操作。我试过 data.foreach 但出现错误。很可能我没有使用正确的 RXjs 运算符。在这方面的任何帮助将不胜感激。
示例数据= [{id:1, 姓名: 'name1'}, {id:2, 姓名: 'name1'}]
loadSucces$ = createEffect(() =>
this.actions$.pipe(
ofType(Actions.loadSuccess),
switchMap(([data]) =>
// data returns an array of objects, from whose id I want to go through
this.service
.get('data.id')
.pipe(
map(serviceData =>
Actions.loadDataSuccess({ serviceData })
),
catchError(error =>
of(Actions.loadDataSuccess({ error }))
)
)
)
)
);
创建您要执行的操作的数组,然后使用 from
在其上调用 mergeMap
。
// ....
mergeMap(([data]) => {
const actions = data.map(item => Actions.someAction(item));
// now actions is an array of actions we want to pass further.
return from(actions);
})
那么每一项操作都将通过商店进行处理。
https://timdeschryver.dev/snippets/multiple-service-calls-from-an-effect
refresh$ = createEffect(() =>
this.actions$.pipe(
ofType(CustomerActions.refresh),
exhaustMap(({ customerIds }) =>
merge(
...ids.map(id =>
this.customersService.getCustomer(id).pipe(
map(CustomerActions.getCustomerSuccess),
catchError(err =>
of(CustomerActions.getCustomerFailed(id, err.message)),
),
),
),
),
),
),
)