ngrx如何在组件中订阅动作或订阅状态

时间:2018-10-03 08:18:04

标签: angular redux ngrx

我通过效果通过动作将对象置于状态:

{
 field1: 'value1',
 field2: 'value2',
}

但是随后,我添加了新字段(通过效果,服务器响应后),redux看起来像:

{
 field1: 'value1',
 field2: 'value2',
 newField: 'this is new field'
}

在组件中,我需要获取最终状态。 我该怎么办??? 订阅存储并在“ newField”就位时获取状态。

@Effect()
  initializeMain$: Observable<Action> = this.actions$.pipe(
    ofAction(AppInitializeAction),
    map(action => {
      const obj = {
		 field1: 'value1',
		 field2: 'value2',
	  }
      return new InitializeObjAction(obj);
    }),
  );

  @Effect()
  addNewFieldToState$: Observable<Action> = this.actions$.pipe(
    ofAction(InitializeObjAction),
    map(action => {
      const newField = {
		 newField: 'This is new field'
	  }
      return new addNewFieldAction(newField);
    }),
  );

我听说过联合减速器...但是我不知道如何使用。 减速器:

   @Action(InitializeObjAction)
	initialize(state: IAppState, action: InitializeObjAction) {
    return { ...state, mainState: action.payload };
   }
   @Action(addNewFieldAction)
	addNewField(state: IAppState, action: addNewFieldAction) {
    return {
      ...state,
      mainState: {
        ...state.mainState,
        newField: action.payload
      }
    };

在组件中我需要:

this.store.select(storeStateWithNewField).subscribe.....

1 个答案:

答案 0 :(得分:2)

您可以使用RxJS filter运算符:

this.store.select(storeStateWithNewField)
.pipe(filter(_ => _.newField !== undefined))
.subscribe...;