类型 'Observable' 不可分配给类型 'any[]'。 属性 'length' 类型 'Observable' 缺失

Type 'Observable' is not assignable to type 'any[]'. Property 'length' is missing in type 'Observable'

在我的 Angular 应用程序中,我通过异步调用提取了一些数据。然后,一旦我有了这些数据,我就有了一个函数(见下文)迭代该数组并为传入的相应 stageName 获取 record_id。然而,我 运行 遇到了一个 ts 错误——stageRecords 下有一个红色波浪线(见下面的星号),错误是:

[ts] Type 'Observable' is not assignable to type 'any[]'.
Property 'length' is missing in type 'Observable'.

这是我的代码:

public async getStageIdByName(stageName)
{
    let stageRecords = [];
    **stageRecords** = await this.getAllStages();
    if (stageName && stageRecords) {
        console.log('stageRecords: ', stageRecords);
        for (let record of stageRecords) {
            if (record.stage === stageName) {
                let stageId = record._id;
                console.log(`stageId for ${stageName} is ${stageId}`);
                return stageId;
            }
        }
    }
}

我需要更改什么来解决这个问题?我尝试使用 Array.from() 但这并没有解决 this 是一个可观察的问题,这显然使这一举动变得不可能。如何解决从对 this.getAllStages() 的响应中获取数组的问题?

更新:根据建议我导入了 toPromise() 运算符,然后将我的代码更改为如下所示:

public async getStageIdByName(stageName)
{
    let stageRecords = [];
    stageRecords = await this.getAllStages().toPromise();
    if (stageName && stageRecords) {
        console.log('stageRecords: ', stageRecords);
        for (let record of stageRecords) {
            if (record.stage === stageName) {
                let stageId = record._id;
                console.log(`stageId for ${stageName} is ${stageId}`);
                return stageId;
            }
        }
    }
}

这似乎是正确的轨道,但是,我现在收到此错误:

Type 'Response' is not assignable to type 'any[]'.
  Property 'length' is missing in type 'Response'.

顺便说一下,我的 getAllStages() 函数如下所示:

public getAllStages()
{
    let stageRecords;
    let recordsArray;
    let fn = response => {
        stageRecords = response.data;
        if (stageRecords) {
            recordsArray = Array.from(stageRecords);

            return recordsArray;
        }
    };

    return this.stageService.getStages((fn));
}

你的getAllStagesreturnsObservable,不是承诺,所以你不能等待。

您可以通过 toPromise() 方法做出承诺,或者订阅它。

如果您使用 rxjs 6 (angular 6) 并且它背后是 http 请求,这应该可以工作,在旧版本中您需要导入该 toPromise 运算符。

stageRecords = await this.getAllStages().toPromise();

在旧版本的 angular 中,您需要像这样导入该运算符

import 'rxjs/add/operator/toPromise';