我对从服务器接收到一组新数据后更新并从reducer返回正确状态感到困惑。在服务器响应之后,我实际上不明白要返回什么(如何更新状态)。 为了更清楚我的困惑:
举个例子:在todo app上我会有一个reducer:
// imports..
export function todoReducer(state = [], action) {
switch (action.type) {
// some cases...
case todoActions.TODO_LOADED: {
return [
...state,
{
...action.payload
}
]
}
// some more cases...
default:
return state;
}
}
和效果:
@Effect() todoList$: Observable<any> = this.action$
.ofType(todoActions.TODO_LOAD)
.switchMap(() => {
return this.http
.get('/rest/todo-list')
.map((todos: Todos) => new todoActions.TodoLoaded(todos))
.catch(err => Observable.of(new todoActions.TodoFailed(err)));
});
当触发 todoActions.TODO_LOAD 时,我显然会得到待办事项列表。直到这里很清楚。
但是,如果用户从UI中删除todo项,如何更新reducer中的状态?我会从我的组件中发送一个 todoActions.TodoRemove 动作,其中包含要删除的todo和...
对于exp:
@Effect() removeTodo$: Observable<any> = this.action$
.ofType(todoActions.TODO_REMOVE)
.switchMap((action : todoActions.TodoRemove) => {
return this.http
.delete(`/rest/todo-list/${action.payload['todoId']}`)
.map(() => {
// What kind of action should I apply here?
})
.catch(err => Observable.of(new todoActions.TodoFailed(err)));
});
所以问题是在服务器成功响应后我应该触发什么样的操作(假设我只得到200)?
如果我再次触发 todoActions.TODO_LOAD 。它会将列表与之前的状态合并,我会得到双待的......
但是我们不应该改变状态......所以每次加载新的待办事项时我都不应该刷新状态......对吗?
或者我只需创建一个像t odoActions.TODO_REMOVE_SUCCESSED 这样的新动作,并从没有状态的服务器返回新的待办事项列表......如:
case todoActions.TODO_REMOVE_SUCCESSED: {
return [...action.payload ]
}
这会是反模式吗?
也许这是一个愚蠢的问题,但我不明白这个想法......
提前致谢!
答案 0 :(得分:1)
我会给出一个更标准,清洁和简单的解决方案。还将解决您的重复问题,并始终正确更新您的商店。
您需要6个动作:
import { Action } from '@ngrx/store';
/* App Models */
import { Todo } from './todo.model';
export const TODO_GET = '[Todo] get todo';
export const TODO_GET_SUCCESS = '[Todo] get todo success';
export const TODO_DELETE = '[Todo] delete todo';
export const TODO_DELETE_SUCCESS = '[Todo] delete todo success';
export const TODO_GET_BY_ID = '[Todo] get todo by id';
export const TODO_GET_BY_ID_SUCCESS = '[Todo] get todo by id success';
// Gets Todos from APIs
export class TodoGetAction implements Action {
readonly type = TODO_GET;
}
// Returns APIs fetched Todos
export class TodoGetSuccessAction implements Action {
readonly type = TODO_GET_SUCCESS;
constructor(public payload: Todo[]) {}
}
// Deletes a Todo given its string id
export class TodoDeleteAction implements Action {
readonly type = TODO_DELETE;
constructor(public payload: string) {}
}
// True -> Success, False -> Error
export class TodoDeleteSuccessAction implements Action {
readonly type = TODO_DELETE_SUCCESS;
constructor(public payload: Todo[]) {}
}
// Takes the id of the todo
export class TodoGetByIdAction implements Action {
readonly type = TODO_GET_BY_ID;
constructor(public payload: string) {}
}
// Returns todo by id
export class TodoGetByIdSuccessAction implements Action {
readonly type = TODO_GET_BY_ID_SUccess;
constructor(public payload: Todo) {}
}
export type All =
| TodoGetAction
| TodoGetSuccessAction
| TodoDeleteAction
| TodoDeleteSuccessAction
| TodoGetByIdAction
| TodoGetByIdSuccessAction;
然后你将拥有一个简单状态的reducer,它有一个todos数组和id选择的当前todo。我们处理所有成功的操作,同时处理效果中的所有正常操作:
import { createFeatureSelector } from '@ngrx/store';
import { createSelector } from '@ngrx/store';
/* ngrx */
import * as TodoActions from './todo.actions';
/* App Models */
import { Todo } from './todo.model';
// Get all actions
export type Action = TodoActions.All;
export interface TodoState {
todos: Todo[];
todoById: Todo;
}
// Initial state with empty todos array
export const todoInitialState: TodoState = {
todos: [],
todoById: new Todo({})
}
/* Selectors */
export const selectTodoState = createFeatureSelector<
TodoState
>('todo');
// Select all Todos
export const selectTodos = createSelector(
selectTodoState,
(state: TodoState) => state.todos
);
export const selectTodoByID = createSelector(
selectTodoState,
(state: TodoState) => state.todoById
);
export function todoReducer(
state: TodoState = todoInitialState,
action: Action
) {
switch (action.type) {
case TodoActions.TODO_GET_SUCCESS:
const oldTodos = state.todos;
// Add new todos to old ones
const newTodos = oldTodos.concat(action.payload);
// Cast to set to have only unique todos
const uniqueTodos = new Set(newTodos);
// Cast back to array to get an array out of the set
const finalTodos = Array.from(uniqueTodos);
return {
...state,
todos: [...finalTodos]
}
case TodoActions.TODO_DELETE_SUCCESS:
return {
...state,
todos: state.todos.filter( todo => return todo.id !== action.payload)
}
case TodoActions.TODO_GET_BY_ID_SUCCESS:
return {
...state,
todoById: state.todos.filter( todo => return todo.id === action.payload)[0]
}
default:
return state;
}
}
然后你将有3个效果:
import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';
import { Store } from '@ngrx/store';
/** rxjs **/
import { mergeMap } from 'rxjs/operators/mergeMap';
import { catchError } from 'rxjs/operators/catchError';
import { map } from 'rxjs/operators/map';
import { of } from 'rxjs/observable/of';
/** ngrx **/
import * as TodoActions from './todo.actions';
import { AppState } from '../app-state.interface';
/** App Services **/
import { TodoService } from './province.service';
@Injectable()
export class TodoEffects {
@Effect()
getTodos$ = this.actions$.ofType(TodoActions.TODO_GET).pipe(
mergeMap(() => {
// I Imagine you can move your api call in such service
return this.todoService.getTodos().pipe(
map((todos: Todo[]) => {
return new TodoActions.TodoGetSuccessAction(todos);
}),
catchError((error: Error) => {
return of(// Handle Error Here);
})
);
})
);
@Effect()
deleteTodo$ = this.actions$.ofType(TodoActions.TODO_DELETE).pipe(
mergeMap((action) => {
return new TodoActions.TodoDeleteSuccessAction(action.payload);
})
);
@Effect()
getTodoByID$ = this.actions$.ofType(TodoActions.TODO_GET_BY_ID).pipe(
mergeMap((action) => {
return new TodoActions.TodoGetByIdSuccessAction(action.payload);
})
);
constructor(
private todoService: TodoService,
private actions$: Actions,
private store: Store<AppState>
) {}
}
最后,在您的Todo组件中,您可以发送和订阅更改,以便从商店中获取最新信息。当然,我假设您有一些方法可以通过id调度新的GetTodoById
传递todo的id来触发研究,还有其他方法以同样的方式处理消除。您在商店中进行的每项修改都将反映到您的组件中通过选择器订阅的条目。
. . .
todos$: Observable<Todo[]>;
todoById$: Observable<Todo>;
constructor(private store: Store<AppState>) {
this.todos$ = this.store.select(selectTodos);
this.todo$ = this.store.select(selectTodoById);
}
ngOnInit() {
this.store.dispatch(new TodoActions.TodoGetAction);
}