1

我有几个分店。让我们说Sub1,并Sub2使用以下状态和减速器(我的问题对我的问题不感兴趣......我猜):

子1:

export interface Sub1State {
  sub1value: string
}

export function sub1reducer(state: Sub1State, action: Action): Sub1State {
  ...
}

子2:

export interface Sub2State {
  sub2value: number
}

export function sub2reducer(state: Sub2State, action: Action): Sub2State {

}

然后我将这两个子状态合并为一个ActionReducerMap<ApplicationState>

export interface ApplicationState {
  sub1: Sub1State,
  sub2: Sub2State
}

export const reducers: ActionReducerMap<ApplicationState> = {
  sub1: sub1reducer,
  sub2: sub2reducer
};

并将其“注册”到商店:

StoreModule.forRoot(reducers)

现在,在 Angular 组件中,我想选择Sub1商店并获取sub1value字符串。所以我做...

sub1value$: Observable<string>;

constructor(private store: Store<Sub1State>) {
  this.sub1value$ = store.map(state => {
    console.log(state);
    return state.sub1value;
  });
}

在日志语句中,我希望得到以下对象(Sub1State 对象):

{
  sub1value: 'initial value'
}

但我真正得到的是这个对象:

{
  sub1: {
    sub1value: 'initial value'
  }
}

这是否按预期工作?如果是,我将如何使用接口 Sub1State?因为sub1不是接口的一部分。

state.sub1value而且很好奇的是,在调用明显错误的内容时,我没有收到任何错误(编译器错误和运行时错误),因为它必须是state.sub1.sub1value. 我理解没有运行时错误,它只是未定义。但在我看来,TypeScript 编译器应该在这里抛出一个错误。

我真的很困惑:/

编辑

这是我期望它如何工作的示例:https ://stackblitz.com/edit/angular-w34kua?file=app%2Fapp.component.ts

4

1 回答 1

1

当您获得应用程序的状态时,它会返回一个对象。您的状态中有两个子状态,它们称为 sub1 和 sub2。每一个都是它自己的对象。所以它按预期工作。你需要做'return state.sub1.sub1value;

或者我通常做的是,我通过执行这样的操作来订阅特定的 reducer,然后我只得到那个特定的子状态而不是整个状态:

constructor(private store: Store<Sub1State>) {
  store.select('sub1').subscribe((state : Sub1State) => {
    console.log(state);
    this.sub1value$ = state.sub1value;
  });
}
于 2017-08-16T16:46:50.207 回答