【问题标题】:How to properly push and receive data from ngrx store如何正确推送和接收来自ngrx存储的数据
【发布时间】:2017-10-13 09:45:02
【问题描述】:

我正在尝试使用 ngrx 商店并遇到问题,以便在我的商店中正确推送数据并选择它。

我的商店对象看起来像

AppStore = {
  chat: {
    messages: []
  }
}

我的减速器看起来像

const initialState = {
  messages: []
};

export const ChatReduce = (state = initialState, action:Action) => {
  if (typeof state === 'undefined') {
    return initialState;
  }
  switch(action.type){
    case 'ADD_MESSAGE':
      return {
        ...state,
        messages: [...state.messages, action.payload]
      };
    default:
      return state;
  }
};

如果“ADD_MESSSAGE”我想从动作有效负载中推送新消息对象并返回新状态。我究竟做错了什么?现在我的状态的聊天消息数组每次推送新消息时都会重写一个值,但旧消息不会保存。

写入存储后,如何选择我状态的消息?是否需要订阅数据?我试过this.store.select('chat'),但如何获取消息?

【问题讨论】:

    标签: angular ngrx ngrx-store


    【解决方案1】:

    我能够在不覆盖的情况下添加它:

    https://jsfiddle.net/seesyong/stL5o0ck/

    如果您只想提取可以执行的消息:

    this.store.select(state => state.chat)
      .subscribe(chat => {
      console.log(chat.messages);
    });
    

    【讨论】:

      【解决方案2】:

      这就是我的方法,

        ngOnInit() {
        this.getStudents();
        this.students$ = this.store.select(state => state.students)
        this.students$.forEach( v => console.log(v))
        }
      
        getStudents(){
        // we want to dispatch na action 
        this.store.dispatch(new studentActions.LoadStudentsAction())
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-15
        • 2021-07-31
        • 1970-01-01
        • 2019-11-12
        • 2019-02-17
        • 2022-01-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多