Ngxs - 从后端加载数据的操作/状态

Gar*_*son 16 angular ngxs

我刚刚开始尝试,ngxs但从我的阅读到目前为止,我还没有100%清楚我应该回调我的API来坚持和读取数据(我看到的所有例子都没有这样做,或者使用一些模拟).

例如,我创建了一个维护项目列表的状态.当我想添加一个项目时,我将'AddItem`动作发送到商店,在那里我将新项添加到状态.这一切都运行正常 - 问题是插入将项目POST到服务器的调用的适当位置在哪里?

我应该在我的动作实现中调用API,即在更新商店的项目列表之前.

或者我应该在我的Angular组件中调用API(通过服务),然后在收到响应时调度"添加项目"操作?

我对这个领域很陌生,所以这些方法的任何指导或优点/缺点都会很棒.

Leo*_*ley 20

最好的地方是你的行动处理程序.

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')),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,我们没有明确的api返回操作,我们根据AddTodo操作响应来改变状态.

如果您愿意,可以将其拆分为三个动作以更明确,

AddTodo,AddTodoCompleteAddTodoFailure

在这种情况下,您需要从http帖子发送新事件.

  • 您可以使用NgxsOnInit生命周期事件来调度LoadTodos操作。然后为此添加一个动作处理程序。如何在文档中进行操作。 (2认同)