无法使用ngrx和Angular从商店加载和显示项目

无法使用ngrx和Angular从商店加载和显示项目,angular,ngrx,ngrx-store,Angular,Ngrx,Ngrx Store,我试图使用Angular和ngrx实现一个存储,但在加载存储中存储的值时遇到了一些问题。我的项目是使用服务加载的,它似乎工作正常 这是我的密码: // app.module.ts StoreModule.forRoot({ todoReducer } // -------------------------- //todo.reducer.ts export function todoReducer(state: TodoState, action: Action) { return

我试图使用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)">
我的问题是,当服务加载所有TODO时,我的组件似乎没有更新。我在html中总是有一个空的项目列表。但在日志中,我可以看到该服务从后端正确检索我的项目

我确实做错了什么,但我不知道是什么。有什么建议吗


PS:我在Angular 8.2.12和ngrx 8.6.0上,您需要将ActionReducerMap传递给StoreModule.forRoot

确保您的状态已初始化:

const initialState = { todos:[], selectedTodo: null };
选择状态片

选择器应从根开始,并包括以下状态:

this.todos = this.store.select(state => state.todoState.todos);
或者更好的是,您应该使用选择器:


您需要将ActionReducerMap传递给StoreModule.forRoot

确保您的状态已初始化:

const initialState = { todos:[], selectedTodo: null };
选择状态片

选择器应从根开始,并包括以下状态:

this.todos = this.store.select(state => state.todoState.todos);
或者更好的是,您应该使用选择器:


我从未见过一个直接选择状态而不是通过选择器的例子,所以我实际上从来没有考虑过。我总是创建选择器。我只是假设,如果你选择这样的状态,结果不会被记忆。我从来没有见过一个例子直接选择状态,而不是通过选择器,所以我实际上从来没有考虑过。我总是创建选择器。我只是假设,如果你选择这样的状态,结果不会被记忆。
this.store.select(selectAll);