3

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.

8
  • Are you using HttpClient? if not then you need res.data Commented Oct 25, 2018 at 12:54
  • import { HttpClientModule } from '@angular/common/http'; Commented Oct 25, 2018 at 13:09
  • Yes, I using HttpCliente. With res.data I get the following error: error TS2339: Property 'data' does not exist on type 'Client[]'. Commented Oct 25, 2018 at 13:10
  • 1
    Try look into the network tab, are you getting the correct response as you said "My Api is returning an Array of objects" Commented Oct 25, 2018 at 13:14
  • @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. Commented Oct 25, 2018 at 13:32

3 Answers 3

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Man! you are a lifesaver hehehe it works like a charm! thanks!
@ThiagoReis but the question still remains as you said "My Api is returning an Array of objects"
1

Try this :

this.clients = res.data;

1 Comment

With res.data I get the following error: error TS2339: Property 'data' does not exist on type 'Client[]'.
-2

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

1 Comment

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.