【问题标题】:Cannot load and display items from the store using ngrx and Angular无法使用 ngrx 和 Angular 从商店加载和显示项目
【发布时间】:2020-11-30 03:50:19
【问题描述】:

我尝试使用 Angular 和 ngrx 实现存储,但在加载存储在存储中的值时遇到了一些问题。我的项目是使用服务加载的,它似乎可以正常工作。

这是我的代码:

// app.module.ts
StoreModule.forRoot({
  todoReducer
}

// --------------------------
//todo.reducer.ts
export function todoReducer(state: TodoState, action: Action) {
  return reducer(state, action);
}

const reducer = createReducer(
  initialState,
  on(TodoActions.BEGIN_GET_TODOS, state => state),
  on(TodoActions.SUCCESS_GET_TODOS, (state: TodoState, {payload}) => {
    return {
      ...state,
      todos: payload,
      selectedTodo: null
    };
  }),
...

// --------------------------
// todo.effects.ts
getTodos$: Observable<Action> = createEffect(() =>
    this.$action.pipe(
      ofType(TodoActions.BEGIN_GET_TODOS),
      mergeMap(() =>
        this.todoService.getTodos().pipe(
          // Success http call
          map((data: Todo[]) =>
            TodoActions.SUCCESS_GET_TODOS({payload: data}),
          ),
          // Error http call
          catchError((error: Error) =>
            of(TodoActions.ERROR_TODOS(error)),
          ),
        )
      )
    )
);

// --------------------------
// todo-list.component.ts
export class TodoListComponent implements OnInit {
    todos: Observable<Array<Todo>>;
    
    ngOnInit(): void {
        this.todos = this.store.select(state => state.todos);
        this.store.dispatch(TodoActions.BEGIN_GET_TODOS());
      }
}

// --------------------------
// todo-list.component.html
<tr *ngFor="let todo of todos | async" (click)="onSelect(todo)">

我的问题是当服务加载所有待办事项时,我的组件似乎没有更新。我总是在 html 中有一个空的项目列表。但在日志中我可以看到该服务正确地从后端检索我的项目...

我肯定做错了什么,但我不知道是什么。有什么建议吗?

PS:我使用的是 Angular 8.2.12 和 ngrx 8.6.0

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    您需要将 ActionReducerMap 传递给StoreModule.forRoot()

    StoreModule.forRoot({ 'todoState', todoReducer });
    

    确保您的状态已初始化:

    const initialState = { todos:[], selectedTodo: null };
    

    选择状态片

    您的选择器应该从根开始并包含状态:

    this.todos = this.store.select(state => state.todoState.todos);
    

    或者更好的是,您应该使用选择器

    export const selectAll = createSelector<any, any, any>(state => state.todoState, todoState => todoState.todos);
    
    

    你可以这样使用:

    this.store.select(selectAll);
    

    【讨论】:

    • 我从未见过直接选择状态而不是通过选择器选择状态的示例,因此我实际上从未考虑过。我一直在创建选择器。我只是假设如果你选择这样的状态,结果将不会被记忆。
    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    相关资源
    最近更新 更多