从后端加载数据的操作/状态 [英] Actions/state to load data from backend
问题描述
我刚刚开始尝试ngxs
,但是到目前为止,我还没有100%清楚我应该在哪里回叫我的API来持久化和读取数据(我所看到的所有示例都是不这样做,或使用一些模拟).
I've just started experimenting with ngxs
but from my reading so far I'm not 100% clear on where I should be calling back to my API to persist and read data (all examples I've seen are either not doing it, or using some mock).
例如我创建了一个维护项目列表的状态.当我想添加项目时,我将"AddItem"操作分派到商店,将新项目添加到状态中.所有这些都可以正常工作-问题是在哪里合适的位置插入将商品过帐到服务器的呼叫中?
E.g. I've created a state where I maintain a list of items. When I want to add an item, I dispatch the 'AddItem` action to the store, where I add that new item to the state. This all works ok - the question is where is the appropriate place to plug in the call that POSTs the item to the server?
我应该在操作实现中(即在更新商店的商品列表之前)调用API.
Should I call the API in my action implementation i.e. just before I update the store's item list.
还是应该在Angular组件中调用API(通过服务),然后在收到响应时调度添加项目"操作?
Or should I call the API in my Angular component (via a service), then dispatch the 'Add Item' action when I received a response?
我在这个领域还很陌生,因此这些方法的任何指导或优点/缺点都将很好.
I'm quite new to this area, so any guidance or pros/cons of these approaches would be great.
推荐答案
最好的位置是您的操作处理程序.
The best place is in your action handler.
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
动作响应对状态进行了变异.
In the example above we don't have a explicit action for the return of the api, we mutate the state based on the AddTodo
actions response.
如果需要,您可以将其分为三个动作以更明确地显示,
If you want you can split it into three actions to be more explicit,
AddTodo
,AddTodoComplete
和AddTodoFailure
在这种情况下,您将需要从http帖子中分发新事件.
In which case you will need to dispatch new events from the http post.
这篇关于从后端加载数据的操作/状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!