0

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 Answers 3

2

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

1 Comment

Thanks, @Suren Srapyan for the quick answer. I appreciate it
0

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:

1 Comment

Thanks @yurzui for your answer! I appreciate it.
0

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

Happy Coding :)

1 Comment

Actually, answer from @Suren Srapyan helped fix my problem. Thanks for your comment though!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.