与所有“ flux体系结构”([actions
,effects
,reducers
等...)和rxjs
结合在一起,我正在尝试创建或删除多个数据 。
我有以下问题:
这里是我在做什么的一个例子:
后台服务:
create(peoples: Array<IPeople>): Observable<Array<IPeople>> {
const https = [];
peoples.forEach((people) => https.push(this.httpClient.post<IPeople>(this.endpoint, people)));
return forkJoin([]);
}
EFFECTS
createAll$ = createEffect(() =>
this.action$.pipe(
ofType(fromPeopleActions.CREATE),
mergeMap((action) => {
return this.backend.create(action.people).pipe(
map((people) => fromPeopleActions.CREATE_SUCCESS({ people })),
catchError((error) => of(fromPeopleActions.CREATE_FAIL({ error: this.requestHandler.getError(error) })))
);
})
)
);
减速器:
const peopleReducer = createReducer(
INIT_STATE,
on(fromPeopleAction.GET_ALL_SUCCESS, fromPeopleAction.CREATE_SUCCESS, fromPeopleAction.DELETE_SUCCESS, (state, { peoples }) => adapter.addMany(peoples, { ...state, loading: false })),
on(fromPeopleAction.GET_ALL_FAIL, fromPeopleAction.CREATE_FAIL, fromPeopleAction.DELETE_FAIL, (state, { error }) => ({ ...state, error, loading: false }))
);
CALL
ngOnInit(): void {
this.peopleDispatchService.getAll();
this.peopleSelectorsService.loading.subscribe((isLoading) => {
if (!isLoading) {
this.peopleSelectorsService.total.subscribe((total) => {
console.log(total);
if (total === 0) {
this.peopleDispatchService.create([
{ id: '0', isMain: true, name: 'THIAGO DE BONIS CARVALHO SAAD SAUD', avatar: 'assets/users/thiagobonis.jpg', messages: null },
{ id: '1', isMain: false, name: 'BILL GATES', avatar: 'assets/users/billgates.jpg', messages: null },
{ id: '2', isMain: false, name: 'STEVE JOBS', avatar: 'assets/users/stevejobs.jpg', messages: null },
{ id: '3', isMain: false, name: 'LINUS TORVALDS', avatar: 'assets/users/linustorvalds.jpg', messages: null },
{ id: '4', isMain: false, name: 'EDSGER DIJKSTRA', avatar: 'assets/users/dijkstra.jpg', messages: null },
])
} else {
this.peopleSelectorsService.allIds.subscribe((ids) => this.peopleDispatchService.delete(ids.toString()));
}
});
}
});
}
您几乎正确地做到了
create(people: Array<IPeople>): Observable<Array<IPeople>> {
return forkJoin(
...people.map(person => this.httpClient.post<IPeople>(this.endpoint, person)),
);
}
[fromPeopleAction.DELETE_SUCCESS
和addMany
也一起听起来很奇怪。我为此添加一个独立的on
。
现在创建将引起创建请求。