1
votes

I have a service who call an API with the following function:

getAll(): Observable<Client[]> {
    return this.http.get<Client[]>(`${this.url}/clients`) 
}

And in my component the service call :

  getClients() {
      this.clientService.getAll().subscribe(
      res => {
         this.clients = res;
         console.log(this.clients);
      },
      err => {
        console.log(err);
      }
);}

With this, I get a response object of objects. My API is returning an Array of objects, but someway the Observable function transforms the data in an object of objects with numeric indices: Console img with error

anyone knows what's the problem?

Solution:

Using KeyValue Pipe is a workaround like commented by @Suryan. The problem was a sort method in my API, which changed the array into an object. It's not necessary to use pipe or map in service, as well not necessary use pipe keyvalue. @Suryan make an example demonstrating this point.

3
Are you using HttpClient? if not then you need res.dataMike Tung
import { HttpClientModule } from '@angular/common/http';Arigui Ahmed
Yes, I using HttpCliente. With res.data I get the following error: error TS2339: Property 'data' does not exist on type 'Client[]'.Thiago Reis
Try look into the network tab, are you getting the correct response as you said "My Api is returning an Array of objects"Suryan
@Suryan My API return is correct. The problem is in Angular. Request the API with Angular 6 version works fine. The problem is only when I update the Angular version for 7.Thiago Reis

3 Answers

3
votes

Using KeyValue Pipe will solve the problem

<div *ngFor="let item of clients | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>
0
votes

Try this :

this.clients = res.data;
-2
votes

Try making the following changes in your .service.ts file

getAll(): Observable<Client[]> {
    return this.http.get<Client[]>(`${this.url}/clients`).map(res=>res.json()); 
}