2016-09-20 46 views
0

试图使此Angular + ngrx store boiler个人项目样板工作,但得到类型错误。错误消息非常简单,但是我无法在不改变可观察类型的情况下解决它。首先,运行npm startAngular2 @ngrx商店确定但可观察到类型令我困惑

app/app.component.ts(29,9): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable<number[]>'. 
    Type '{}' is not assignable to type 'number[]'. 
    Property 'length' is missing in type '{}'. 

线29时,在这里不用误差在构造函数中和是:

constructor( 
    private store: Store<AppState> 
){ 
    this.counter$ = store.select('counter'); // Line 29 
} 

在代码中,如果我更改从下面观察的类型:

counter$: Observable<number>; 

收件人:

counter$: Observable<any>; 

npm start运行就像一个魅力,但我想知道为什么,因为我试图迫使在Obserbable

编辑号码类型:加减速代码:

import { ActionReducer, Action } from '@ngrx/store'; 

export const INCREMENT = 'INCREMENT'; 

export const counterReducer: ActionReducer<number> = (state: number = 0, action: Action) => { 
    switch (action.type) { 
     case INCREMENT: 
      return state + 1; 
     default: 
      return state; 
    } 
} 

回答

1

要快速解决,这将是通用添加到选择又名地图运营商的商店,像这样

this.counter$ = store.select<number>('counter'); // Line 29 

我认为正在发生的事情是,当你做选择的方式,你怎么办呢TypeScript不能推断出类型。

另一种方法来做到这一点,所以它可以推断类型是做这样的选择器。

this.counter$ = store.select(state$ => state$.counter); // Line 29 

第二个将传递状态对象,你可以从中选择特定的reducer。我不积极,但我认为它应该能够通过这种方式来推断这种类型。

1

没有看到您的更多的代码很难确切地知道发生了什么,但它看起来像你的store.select('counter')返回一个对象的可观察值,在那里你输入counter$作为一个数字的可观察值。当您使用store.select('reducerName')时,商店会向您返回您从reducer函数返回的最后一个值的可观察值。如果要初始化的状态,以一个空的对象,例如

export const counter = (state = {}, action) => {

,可能导致您所看到的错误,你可以尝试,而不是你的初始化状态,您观察到期待的类型。

+0

谢谢@Alex,粘贴减速器代码。仍然无法完全取得突破 – FRECIA