类型对象不可分配为any [] [英] Type object is not assignable to type any[]

查看:73
本文介绍了类型对象不可分配为any []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PrimeNG数据表.我在Angular中使用httpClient从JSON占位符中获取一些模拟数据.它在我的控制台中显示为对象数组,但是Visual Studio Code错误表示它是一个对象.错误显示类型对象不可分配给any [].".这是什么问题?

I am using PrimeNG datatable. I using httpClient in Angular to fetch some mock data from JSON Placeholder. It appears in my console as an array of objects, however the Visual Studio Code error is saying it is an object. The error says 'type Object is not assignable to any[].' What is the problem here?

table-layout.component.ts

table-layout.component.ts

import { BrowserModule } from '@angular/platform-browser'
import { Component, OnInit, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http'

@Component({
  selector: 'app-table-layout',
  templateUrl: './table-layout.component.html',
  styleUrls: ['./table-layout.component.css']
})

export class TableLayoutComponent implements OnInit {

  ROOT_URL: string = 'https://jsonplaceholder.typicode.com/users'
  results: any[]

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.getData();
  }

  getData() {
    this.http.get(this.ROOT_URL).subscribe(data => {
      this.results = data
      console.log(this.results) //this is an array in the console 
    })
  }

}

table-layout.component.html

table-layout.component.html

<p-dataTable [value]="results">
</p-dataTable>

推荐答案

如果您未指定从http请求返回的类型,则http客户端将假定其为Object.这导致您看到的类型不匹配错误.您正在尝试将类型Object分配给类型any[].您可以通过执行以下操作指定返回类型

If you do not specify the type that is returned from your http request, the http client assumes its an Object. This is causing the type mismatch error that you are seeing. You are trying to assign type Object to type any[]. You can specify the return type by doing

this.http.get<any[]>(this.ROOT_URL).subscribe(...);

这篇关于类型对象不可分配为any []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆