我刚刚开始尝试使用ngxs但是从我的阅读到目前为止,我并不是100%清楚我应该回调我的API以保持和读取数据(我看到的所有例子都没有这样做,或者使用一些模拟).
例如.我创建了一个状态,我维护一个项目列表.当我想添加一个项目时,我将’AddItem`动作发送到商店,在那里我将新项添加到状态.这一切都运行正常 – 问题是插入将项目POST到服务器的调用的适当位置在哪里?
我应该在我的动作实现中调用API,即在我更新商店的项目列表之前.
或者我应该在我的Angular组件中调用API(通过服务),然后在收到响应时调度“添加项”操作?
我对这个领域很陌生,所以这些方法的任何指导或利弊都会很棒.
最好的地方是你的行动处理程序.
- import { HttpClient } from '@angular/common/http';
- import { State,Action,StateContext } from '@ngxs/store';
- import { tap,catchError } from 'rxjs/operators';
- //
- // todo-list.actions.ts
- //
- export class AddTodo {
- static readonly type = '[TodoList] AddTodo';
- constructor(public todo: Todo) {}
- }
- //
- // todo-list.state.ts
- //
- export interface Todo {
- id: string;
- name: string;
- complete: boolean;
- }
-
- export interface TodoListModel {
- todolist: Todo[];
- }
-
- @State<TodoListModel>({
- name: 'todolist',defaults: {
- todolist: []
- }
- })
- export class TodoListState {
- constructor(private http: HttpClient) {}
-
- @Action(AddTodo)
- FeedAnimals(ctx: StateContext<TodoListModel>,action: AddTodo) {
- // ngxs will subscribe to the post observable for you if you return it from the action
- return this.http.post('/api/todo-list').pipe(
- // we use a tap here,since mutating the state is a side effect
- tap(newTodo) => {
- const state = ctx.getState();
- ctx.setState({
- ...state,todolist: [ ...state.todolist,newTodo ]
- });
- }),// if the post goes sideways we need to handle it
- catchError(error => window.alert('could not add todo')),);
- }
- }
在上面的示例中,我们没有显式的api返回操作,我们根据AddTodo操作响应改变状态.
如果您愿意,可以将其拆分为三个动作以更明确,
AddTodo,AddTodoComplete和AddTodoFailure
在这种情况下,您需要从http帖子发送新事件.