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

前端之家收集整理的这篇文章主要介绍了angular – Ngxs – 从后端加载数据的操作/状态前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始尝试使用ngxs但是从我的阅读到目前为止,我并不是100%清楚我应该回调我的API以保持和读取数据(我看到的所有例子都没有这样做,或者使用一些模拟).

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

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

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

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

最好的地方是你的行动处理程序.
  1. import { HttpClient } from '@angular/common/http';
  2. import { State,Action,StateContext } from '@ngxs/store';
  3. import { tap,catchError } from 'rxjs/operators';
  4.  
  5. //
  6. // todo-list.actions.ts
  7. //
  8. export class AddTodo {
  9. static readonly type = '[TodoList] AddTodo';
  10. constructor(public todo: Todo) {}
  11. }
  12.  
  13.  
  14. //
  15. // todo-list.state.ts
  16. //
  17. export interface Todo {
  18. id: string;
  19. name: string;
  20. complete: boolean;
  21. }
  22. export interface TodoListModel {
  23. todolist: Todo[];
  24. }
  25. @State<TodoListModel>({
  26. name: 'todolist',defaults: {
  27. todolist: []
  28. }
  29. })
  30. export class TodoListState {
  31.  
  32. constructor(private http: HttpClient) {}
  33. @Action(AddTodo)
  34. FeedAnimals(ctx: StateContext<TodoListModel>,action: AddTodo) {
  35.  
  36. // ngxs will subscribe to the post observable for you if you return it from the action
  37. return this.http.post('/api/todo-list').pipe(
  38.  
  39. // we use a tap here,since mutating the state is a side effect
  40. tap(newTodo) => {
  41. const state = ctx.getState();
  42. ctx.setState({
  43. ...state,todolist: [ ...state.todolist,newTodo ]
  44. });
  45. }),// if the post goes sideways we need to handle it
  46. catchError(error => window.alert('could not add todo')),);
  47. }
  48. }

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

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

AddTodo,AddTodoComplete和AddTodoFailure

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

猜你在找的Angularjs相关文章