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

Categories

0 votes
1.3k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...