0
votes

I need a small help regarding Angular 6 HttpClient. I am having a problem with the response from the REST API calls. I am using HttpClient. I have a function which fetches the list of all the users(in my case I call it leads).

fetchLeadsList(){
  return this.http.get('http://localhost:3000/api/leads')
                  .pipe(
                     map(data => {
                        console.log(data);
                        return data;          
                     }));
}

In OnInit of my component, I'm calling this endpoint as:

this.leadsService.fetchLeadsList()
                 .subscribe(response => {
                    console.log(response, 'leadsList');
                    this.leadsList = response.data; // leadList is declared as an empty array 
                 });

I am getting the list of the leads as: enter image description here

However, when I try to map the response from the service as mentioned in the component above(this.leadsList = response.data), I get an error as:

ERROR TS2339: Property 'data' does not exist on type 'Object'.

Since, there is the data property as shown in the image, how come it is giving me an error?

And I am able to display the list in the view as well! Is there something I am missing?

3

3 Answers

2
votes

You need to tell to the compiler what type response have. You can create a type for it or just set it to any to let compiler pass your code

this.leadsService.fetchLeadsList()
    .subscribe((response: any) => {
      console.log(response, 'leadsList');
      this.leadsList = response.data; // leadList is declared as an empty array
})
0
votes

The HttpClient.get() method parsed the JSON server response into the anonymous Object type. It doesn't know what the shape of that object is.

You can specify to which model you want to cast the result:

fetchLeadsList() {
    return this.http.get<{ data: any[] }>('http://localhost:3000/api/leads')
                         ^^^^^^^^^^^^^

See also:

0
votes

try accessing like response['data'] hope this will solve your problem

Happy Coding :)