我想通过连接到 store 来更新我的 Observable,但是当 store 获得值时它没有更新:
在我的组件中,我将任务声明为 Observables:
tasks$: Observable<any> = this.store.pipe(select(state => {
console.log('state', state);
return state;
})); // Worked, get the full state
tasks$: Observable<TaskModel[] | undefined> = this.store.select(selectTasks);
// Doesn't work, can't select tasks from state
减速器:
const tasksReducers = createReducer(
initialState,
on(getTasks, (state) => ({...state, isLoading: true})),
on(getTasksSuccess, (state, result) => ({...state, tasks: result.tasks, isLoading: false}))
);
选择器:
export const selectTasksState = (state: TasksState) => state;
export const selectTasks = createSelector(
selectTasksState,
(state: TasksState) => state.tasks
);
效果:
getTasks$ = createEffect(() =>
this.actions$.pipe(
ofType(getTasks),
exhaustMap(action => this.tasksService.getTasks().pipe(
tap(response => console.log('response', response)),
map(tasks => getTasksSuccess({tasks})),
catchError((error: any) => of(getTasksFailure(error)))
))
)
);
操作:
export const getTasks = createAction(TasksActionTypes.GET_TASKS);
export const getTasksSuccess = createAction(TasksActionTypes.GET_TASKS_SUCCESS, props<{tasks: TaskModel[]}>());
export const getTasksFailure = createAction(TasksActionTypes.GET_TASKS_FAILURE, props<{message: string}>());
状态:
export interface TasksState {
tasks?: TaskModel[],
isLoading?: boolean;
isLoadingSuccess?: boolean;
isLoadingFailure?: boolean;
}
我认为选择器没有看到状态变化,所以它没有更新,但是在减速器中,我已经创建了一个新对象,所以我不确定我错在哪里
答案 0 :(得分:0)
你可以这样做。
在 TS 文件中
selectedData: any;
ngOnInit(): void {
this.selectedStoreData$ = this.store.select(selectorStoreData);
this.selectedStoreData$.subscribe((data: any) => {
if (data) {
this.selectedData= data;
}
});
}
它将订阅数据并将数据存储到 selectedData