【问题标题】:Angular2 @ngrx Store ok but observable type confuses meAngular2 @ngrx 可以存储,但可观察类型让我感到困惑
【发布时间】:2016-09-20 15:23:08
【问题描述】:

试图使这个Angular + ngrx store boiler 个人项目样板工作,但得到一个打字错误。错误消息非常简单,但如果不更改可观察对象的类型,我就无法解决它。首先,运行npm start时出现错误

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;
    }
}

【问题讨论】:

    标签: angular rxjs observable ngrx


    【解决方案1】:

    对此的快速解决方法是将泛型添加到商店中的 select aka map 运算符中

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

    我认为正在发生的事情是,当您以您的方式进行选择时,TypeScript 无法推断类型。

    为了推断类型,另一种方法是像这样使用选择器。

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

    第二个将传入状态对象,您可以从中选择特定的reducer。我不是很肯定,但我认为它应该能够以这种方式推断类型。

    【讨论】:

      【解决方案2】:

      如果没有看到更多代码,很难确切知道发生了什么,但您的 store.select('counter') 似乎正在返回一个对象的可观察对象,您在其中键入 counter$ 作为数字的可观察对象。当你使用store.select('reducerName') 时,store 会返回一个你的 reducer 函数返回的最后一个值的 observable。如果您将状态初始化为空对象,例如

      export const counter = (state = {}, action) =&gt; {

      这可能会导致您看到的错误,您可以尝试将您的状态初始化为您的 observable 所期望的类型。

      【讨论】:

      • 谢谢@Alex,粘贴reducer代码。仍然无法完全了解这里发生了什么
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多