试图将数组保存到 ngrx 状态

trying to save an array to ngrx state

我正在尝试保存从 api 调用中获得的数组,使用 ngrx 效果,然后简单地 *ngfor 该数组。我正在尝试使用 ngrx,但它让事情变得更复杂。我正在将一个数组传递到减速器中,但是 state.comics 显示为 comics: [0: {0: {..}, 1:{..}],而我想要的只是 comics: [0: {..}, 1: {..}]j。所以 reducer 并没有将数组保存到漫画中,而是将其推送到 0 然后创建更多对象。

comics.data.results 是一个数组

动作:

import { createAction, props } from '@ngrx/store';

export const getComics = createAction('[Comics] Get comics');
export const getComicsSuccess = createAction(
  '[Comics] Success Get Comics',
  (comics: any) => comics
);

effects.ts

@Injectable()
export class ComicEffects {
  loadComics$ = createEffect(() =>
    this.action$.pipe(
      ofType(getComics),
      exhaustMap(() =>
        this.dataService.getComics().pipe(
          map((comics) => {
            console.log(comics.data.results);
            return getComicsSuccess(comics.data.results);
          })
          /* catchError(() => EmptyError) */
        )
      )
    )
  );

  constructor(
    private action$: Actions,
    private dataService: MarvelServiceService
  ) {}
}

减速器:

import { createReducer, on } from '@ngrx/store';
import { getComicsSuccess } from '../Actions/comics.action';

const initialState: any = [];

export const comicReducer = createReducer(
  initialState,
  on(getComicsSuccess, (state, data) => [...state, data])
);

html:

<ul>
  <li *ngFor="let comic of comics$ | async; index as i">
    {{ i + 1 }}
  </li>
</ul>

组件:

export class ComicsComponent implements OnInit {
  comics$ = this.store.select((state) => state.comics);

  constructor(private store: Store<any>) {}

  ngOnInit() {
    this.getAllComics();
  }

  getAllComics() {
    this.store.dispatch(getComics());

  }
}

app.module:

 StoreModule.forRoot({ comics: comicReducer }),

我猜 comics.data.results 也是一个数组。

因此,如果您需要将其保存在状态中,您也需要对其使用扩展运算符。所以它可以是一个数组。

// Action
import { createAction, props } from '@ngrx/store';

export const getComicsSuccess = createAction('[Comics] Success Get Comics', props<{ comics: any[] }>());

// Effect
this.dataService.getComics().pipe(
  map((getComics: any) => {
    return getComicsSuccess({ comics: getComics.data.results });
  })
);

//Reducer
export const comicReducer = createReducer(
  initialState,
  on(getComicsSuccess, (state, {comics}) => [...state, ...comics])
);

如果您输入您的操作,它会有所帮助。 comics: any 会搬起石头砸你的脚,就像现在一样。

我猜应该和这个差不多

export const comicReducer = createReducer(
  initialState,
  on(getComicsSuccess, (state, action) => [...state, action.comics])
);