【发布时间】: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