简体   繁体   中英

Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.ts

I got error in visual studio code ->

Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.ts

I dont know reaseon but check my code:

  trainingPlanResponse: any[] = [];


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

When i set to

trainingPlanResponse: any; 

This work but I need to set in html

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

Important: I don't have model interface for this!

A response from an http request returns an Observable of type Object

Example

Lets say you have a function postToGetData()

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

Typescript will infer the function postToGetData to return an Observable<Object>

The easiest solution to this is to simply use type casting like below

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

The above will infer postToGetData to return any[]

You may also define the return type of the function as any[]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM