首页 > 解决方案 > 如何使用选择器为多个状态获取正确的切片数据并在组件内部使用它们 | ngRx | 还原 | 角 6 | 打字稿

问题描述

我将使用 angular 6 和 ngrx v6 创建一个应用程序。我创建了以下应用程序状态。

app.module.ts

  StoreModule.forRoot({'user': userReducer, 'events': eventsReducer}),

app.state.ts

import { UsersState } from '@app/reducers/users.reducers';
import { EventsState } from '@app/reducers/events.reducers';

export interface AppState{
    user:UsersState,
    events:EventsState
}

users.reducers.ts

export interface UsersState {
    lastInteractionTime: number,
    bookmarksId: object
}

const intialState: UsersState = {
    lastInteractionTime: time,
    bookmarksId: {}
}

export function userReducer(state = intialState, action: usersActions.Action): UsersState{
  switch (action.type) {
    case usersActions.LOAD_USERS:{
      return Object.assign({}, action.payload, state);
      // return action.payload;
    }
    default:{
      return state;
    }
  }
}

events.reducers.ts

import { AppState } from '@app/app-state';

export interface EventsState {
  data: Array<Object>;
}

const intialState: EventsState = {
  lastInteractionTime: time,
  data: []
}


export function eventsReducer(state = intialState, action: eventsActions.Action): EventsState{
  switch (action.type) {
    case eventsAction.LOAD_EVENTS:{
      return Object.assign({}, action.payload, state);
      // return action.payload;
    }
    default:{
      return state;
    }
  }
}

export const selectUser = (state: AppState) => state.user;

export const selectEvents = (state: AppState) => state.events;

export const eventsByUser_ = createSelector(
  selectUser,
  selectEvents,
  (user, events) => {
      console.log('User: ' + JSON.stringify(user));
      /*
        add some logic, filter the data and return events by user's bookmark property.bookmark
      */
      return events.all[user.bookmarksId];
    }
)

当应用程序启动时,我调度调用我的 API 的 LoadUserAction 操作并返回带有 bookmarksId 属性的用户对象。

AppComponent@ngOnInit()

this.userData = this.userService.getUser().subscribe(
      data => {
        this.userData = data.response;
        if(this.userData) {
          this.store.dispatch(new LoadUserAction(this.userData));
        }
      },
      err  => {
        console.log(err);
      }
    );

问题:但是在 HomeComponent 中,我想根据用户的 bookmarksId 属性获取用户的事件。我没有得到用户的数据只是因为可能是API的响应没有返回。

主页组件.ts

export class HomeComponent implements OnInit {
  constructor(private eventService:EventService) {

  }
}
ngOnInit() {
  this.eventService.getData(
    data => {
       this.store.dispatch(loadEventData(data));
    },
    err  => {
      console.log(err);
    }
  );
  this.store.pipe(select(eventsByUser_)).subscribe(
    console.log // it consoles the empty as because the user is always returning initial state with bookmarksId as empty object {}.
  )
}

事件服务.ts

getData(){
  ...
  return eventsData //Observable of data.
}

我是否需要将订阅方法“eventsByUser_”放在其他地方?如何确保“eventsByUser_”选择器仅在用户切片有数据时才起作用。

标签: angulartypescriptreduxngrxngrx-store

解决方案


推荐阅读