Angular 4 cannot select State from Store

101 Views Asked by At

I have a NGRX store and I want to pass a mapping function to the select() to select some data from it.

The interface I want to fetch from is this one:

export interface Thread {
    id: number;
    messageIds: number[];
    participants: {[key: number]: number};
}

I manage to get some other data from the Store via the mapping functions mapStateToUserName and unreadMessagesCounter but for some reason stateToThreadSummariesSelector is not working.

When I try to log the state inside the stateToThreadSummariesSelector it is undefined.

ApplicationState interface:

export interface ApplicationState {
    uiState: UiState;
    storeData: StoreData;
}

code:

  userName: Observable<string>;
  unreadMessagesCounter: Observable<number>;
  threadSummaries: Observable<ThreadSummary[]>;

  constructor(private threadsService: ThreadsService, private store: Store<ApplicationState>) {
    this.userName = store.skip(1).map(this.mapStateToUserName)
    this.unreadMessagesCounter = store.skip(1).map(this.mapStateToUnreadMessagesCounter)

    this.threadSummaries = store.select(this.stateToThreadSummariesSelector)
  }

  stateToThreadSummariesSelector(state: ApplicationState) {
      console.log(state) // undefined

      const threads = _.values<Thread>(state.storeData.threads)

      return threads.map(_.partial(this.mapThreadToThreadSummaries, state));
  }

  mapThreadToThreadSummaries(state: ApplicationState, thread: Thread): ThreadSummary {
    const names = _.keys(thread.participants).map(participantId => state.storeData.participants[participantId].name)
    const lastMessageId = _.last(thread.messageIds)
    const lastMessage = state.storeData.messages[lastMessageId]

    return {
        id: thread.id,
        participantNames: _.join(names, ","),
        lastMessageText: lastMessage.text,
        timestamp: lastMessage.timestamp
    }
  }

  mapStateToUserName(state: ApplicationState): string {
    return state.storeData.participants[state.uiState.userId].name
  }

  mapStateToUnreadMessagesCounter(state: ApplicationState): number {
    const currentUserId = state.uiState.userId;

    return _.values<Thread>(state.storeData.threads).reduce((acc, thread) => acc + thread.participants[currentUserId], 0)
  }
0

There are 0 best solutions below