【发布时间】:2021-09-29 17:54:26
【问题描述】:
我正在尝试使用 ngrx 效果保存从 api 调用获得的数组,然后简单地 *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
);
效果.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 }),
【问题讨论】: