@ngrx 4商店退货类型

时间:2017-08-03 17:27:29

标签: angular typescript redux ngrx

我正在使用Angular 4和@ngrx 4创建一个Web应用程序,我遇到了Store返回类型的问题。这是我使用Store

的组件
export class ProductEditComponent implements OnInit, OnDestroy {

  categoryMap: Map<number, Node>;
  categoryObs$: Observable<State>;
  categoryObsSubscription;

  constructor(private store: Store<State>) { }

  ngOnInit() {
    // Retrieve data from the backend.
    this.categoryObs$ = this.store.select('productTree');
    this.categoryObsSubscription = this.categoryObs$.subscribe((res: State) => {
      this.categoryMap = res.productTree;
    }, (error) => {
      console.error(error);
    });

    this.store.dispatch(new productTreeActions.LoadProductTreeAction(1));
  }

  ngOnDestroy() {
    this.categoryObsSubscription.unsubscribe();
  }

}

根据我对文档的理解,我从store.select获取的观察者应该输入State接口,因为我创建了Store:{{1} }

但是当我尝试将我的observable分配给选定的store: Store<State>Store)时,我收到此错误:

this.categoryObs$ = this.store.select('productTree');

我不确定我做错了什么,因为我检查了Type 'Store<Map<number, Node>>' is not assignable to type 'Observable<State>'. Types of property 'operator' are incompatible. Type 'Operator<any, Map<number, Node>>' is not assignable to type 'Operator<any, State>'. Type 'Map<number, Node>' is not assignable to type 'State'. Property 'productTree' is missing in type 'Map<number, Node>'. 的值,它对应于res类。

这是我的redux:

State

行动:

export interface State {
  productTree: Map<number, Node>;
  errorMsg: string;
}

const initialState: State = {
  productTree: new Map<number, Node>(),
  errorMsg: ''
};

export function productTreeReducer(state = initialState, action: productTreeOperations.Actions): State {

  switch (action.type) {
    case productTreeOperations.LOAD_PRODUCT_TREE:
      return initialState; // Reset state

    case productTreeOperations.LOAD_PRODUCT_TREE_COMPLETE:
      return { productTree: action.payload, errorMsg: '' };

    case productTreeOperations.LOAD_PRODUCT_TREE_FAIL:
      return { productTree: undefined, errorMsg: action.payload }

    case productTreeOperations.DELETE_BRANCH:
      return deleteBranch(action.payload, state);

    case productTreeOperations.ADD_CHILD:
      return addChild(action.payload.parent, action.payload.newChild, state);

    default:
      return state;
  }
}

1 个答案:

答案 0 :(得分:2)

您的州由productTree类型Map<number, Node>

组成
export interface State {
  productTree: Map<number, Node>;
  errorMsg: string;
}

您正在从商店中选择productTree

this.categoryObs$ = this.store.select('productTree');

因此,它将返回Map<number, Node>而不是Observable<State>

相反,您应该使用createFeatureSelector返回状态,然后订阅它,如下例所示。

 // reducers.ts
import { createSelector, createFeatureSelector } from '@ngrx/store';

export interface FeatureState {
  counter: number;
}

export interface AppState {
  feature: FeatureState
}

export const selectFeature = createFeatureSelector<FeatureState>('feature');

并在您的Component中使用此selectFeature

store.select(selectFeature).subscribe(store =. {
  this.counter = store.counter;
});

Read about selectors from here