Type object is not assignable to type any[]

2020-02-15 06:34发布

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

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

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

1条回答
你好瞎i
2楼-- · 2020-02-15 07:04

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(...);
查看更多
登录 后发表回答