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



我刚刚开始尝试ngxs,但是从我的阅读中,我还没有100%清楚我应该回到我的API以持续并读取数据(所有示例我见过的是不这样做,或者使用一些模拟(。

例如。我创建了一个维护项目列表的状态。当我想添加一个项目时,我将"添加剂"操作派遣到商店中,在那里将新项目添加到该州。这一切都很好 - 问题是插入将项目发布到服务器的呼叫的适当位置?

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

或者我应该在我的角组件中调用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动作响应来突变状态。

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

AddTodoAddTodoCompleteAddTodoFailure

在这种情况下,您需要从HTTP帖子中派遣新事件。

如果要将效果与商店分开,则可以定义一个基本状态类:

@State<Customer>( {
    name: 'customer'
})
export class CustomerState {
    constructor() { }
    @Action(ChangeCustomerSuccess)
    changeCustomerSuccess({ getState, setState }: StateContext<Customer>, { payload }: ChangeCustomerSuccess ) {
        const state = getState();
       // Set the new state. No service logic here.
       setState( {
           ...state,
           firstname: payload.firstname, lastname: lastname.nachname
       });
    }
}

然后,您将从该状态派生并将您的服务逻辑放入派生类中:

@State<Customer>({
    name: 'customer'
})
export class CustomerServiceState extends CustomerState {
    constructor(private customerService: CustomerService, private store: Store) {
        super();
    }
    @Action(ChangeCustomerAction)
    changeCustomerService({ getState, setState }: StateContext<Customer>, { payload }: ChangeCustomerAction) {
        // This action does not need to change the state, but it can, e.g. to set the loading flag.
        // It executes the (backend) effect and sends success / error to the store.
        this.store.dispatch( new ChangeCustomerSuccess( payload ));
    }
}

我在我查看的任何NGXS示例中都没有看到这种方法,但是我正在寻找一种分开这两个问题的方法-UI和后端。

最新更新