【问题标题】:Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.ts“Object”类型缺少“any[]”类型的以下属性:length、pop、push、concat 和 26 more.ts
【发布时间】:2021-02-04 06:31:42
【问题描述】:

我在 Visual Studio 代码中遇到错误 ->

类型“Object”缺少类型“any[]”中的以下属性:length、pop、push、concat 和 26 个以上。ts

我不知道原因,但请检查我的代码:

  trainingPlanResponse: any[] = [];


  this.service.postToGetData(model).subscribe(
    data => {
      // this.trainingPlanResponse.push(data);
      this.trainingPlanResponse = data; // HERE IS ERROR!!!
    },
    err => {
      console.log(err) 
    }
  )

当我设置为

trainingPlanResponse: any; 

这项工作,但我需要在 html 中设置

        <div *ngIf="trainingPlanResponse.length > 0">
            response 
        </div>

重要提示:我没有这个的模型接口!

【问题讨论】:

  • 试试this.trainingPlanResponse = data as any[];
  • 你能显示 postToGetData 代码吗?
  • 是的,这是可行的,但我想知道为什么会出错?发生了什么?可以不用界面设置吗?
  • @VladimirBozhinovski 这并不重要 它是 const modelPost = { id: thisi , name: this.name ...}
  • 试试这样的 -> this.trainingPlanResponse = data || []

标签: javascript html angular typescript


【解决方案1】:

来自 http 请求的响应返回 Object 类型的 Observable

示例

假设你有一个函数postToGetData()

postToGetData() {
  return this.httpClient.get('my-url')
}

Typescript 将推断函数postToGetData 返回一个Observable&lt;Object&gt;

最简单的解决方案是简单地使用 类型转换,如下所示

postToGetData() {
  return this.httpClient.get<any[]>('my-url')
}

上面会推断postToGetData返回any[]

您也可以将函数的返回类型定义为any[]

postToGetData(): any[] {
  return this.httpClient.get('my-url').pipe(map(items => items as any[]))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 2022-01-24
    • 2019-12-24
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2021-10-02
    相关资源
    最近更新 更多