Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

angular - Type object is not assignable to type 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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(...);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...