如何使用带参数的选择器在效果中选择表单 ngrx 存储

ALG*_*GDB 6 rxjs ngrx ngrx-effects angular

我需要构建一个 Effect 并且我需要一个来自商店的值,问题是选择器是一个带参数的选择器。

按照示例代码:

        @Effect()
      ExampleEffect$ = this.actions$.pipe(
        ofType(
          ActionTypes.SOMETHING
        ),
        map((action: Somthing) => action.payload.myParameter),
// HERE I NEED THE PARAMETER TO PERFROM THE SELECTION
        withLatestFrom(this.store.pipe(select(selectorWithParamter(myParameter))),
        map((value) => /* do somthing with the array [myParameter, valueSelected from sotre]*/)
Run Code Online (Sandbox Code Playgroud)

rij*_*jin 9

您可以编写一个箭头函数来在创建选择器时传递参数。

export const getAlbumById = (collectionId: number) => createSelector(getAlbumEntities, entities => entities[collectionId]);
Run Code Online (Sandbox Code Playgroud)

更多例子

// 影响

@Effect({ dispatch: true })
  upsertAlbum$ = this.actions$.pipe(
    ofType(AlbumActionTypes.UpsertAlbum),
    map((action: any) => action.payload),
    mergeMap(({ album }) =>
      this.store.pipe(
        select(selectAlbumIfExists(album.id)),
        first(),
        map(isAlbumHasName => [album, isAlbumHasName])
      )
    ),
    filter(([album, isAlbumHasName]) => !isAlbumHasName),
    map(([album]) => new LoadAlbum({ album }))
  );
Run Code Online (Sandbox Code Playgroud)

// 选择器

export const selectAlbumIfExists = (id: string) =>
  createSelector(
    selectAlbumsEntities,
    entities => !!(entities[id] && entities[id].name)
  );
Run Code Online (Sandbox Code Playgroud)


Dra*_*ica 6

您可以创建特定的选择器并在调用时使用它们withLatestFrom

 approve$ = createEffect(() => {
    return this.actions$.pipe(
      ofType(myactions.approve),
      withLatestFrom(this.store.select(selectReference), this.store.select(selectWork)),
      switchMap(([_, reference, work]) => this.service.approve(reference, work)),
      map(() => actions.approveSuccess())
    );
  });
Run Code Online (Sandbox Code Playgroud)

正如上面所建议的,尝试使用选择器。就我而言,

选择参考

选择工作

是 NGRX 选择器,代码如下所示:

//create slice
const requestState= createFeatureSelector<IRequestState>(feature);

//get exactly what you need from the state, not extra stuff
export const selectReference= createSelector(requestState, (state) => state?.reference);

export const selectWork= createSelector(requestState, (state) => state.Work);
Run Code Online (Sandbox Code Playgroud)

保持干净,不要重复选择代码。我怀疑你需要带有参数的选择器。尝试在选择器中获取列表并通过另一个选择器获取参数。在 switchMap 函数中执行逻辑(或者最适合您的函数,mergeMap 或 concatMap)