0

I am trying to retrieve data from a dummy url and map the data into a list. To test the data, I want to display them in an alert/Loop. I am using this dummy api url: http://dummy.restapiexample.com/api/v1/employees

It returns data in this format:

{"status":"success","data":[{"id":"1","employee_name":"Tiger 
Nixon","employee_salary":"320800","employee_age":"61","profile_image":""}, 
{"id":"2","employee_name":"Garrett 
Winters","employee_salary":"170750","employee_age":"63","profile_image":""} ...

Below is my typescript code:

constructor(private http: HttpClient) { }
configUrl = 'http://dummy.restapiexample.com/api/v1/employees';
getEmployees() {
var x = this.http.get<Employee[]>('http://dummy.restapiexample.com/api/v1/employees').pipe(map(res => 
res['data']));
alert(JSON.stringify(x));
}

This is my class Employee:

export class Employee {
id: any;
employee_name: any;
employee_salary: any;
employee_age: any;
profile_image: any;
}

Based on my research, we should use the pipe(map(res =>res['data']), but it is not working for me. Anyone can help understand what is wrong with the above code please?

avdeveloper
  • 449
  • 6
  • 30
  • See the aforementioned [suggested duplicate](https://stackoverflow.com/q/14220321/1260204). Asynchronous calls are a common and critical building block in writing/designing an application. It is critical that you understand how to work with asynchronous calls in javascript, and by extension typescript. Understanding these core concepts will help you become a better programmer and also ensure you do not keep "stubbing your toe" on the same problem. – Igor Apr 27 '20 at 15:34
  • Also Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/1260204) – Igor Apr 27 '20 at 15:34

1 Answers1

0

You don't need to map data in the new version of HttpClient. So that means there is no need for a pipe operator here. Also, you need to subscribe to actually receive the data.

See below:

constructor(private http: HttpClient) { }
configUrl = 'http://dummy.restapiexample.com/api/v1/employees';
getEmployees() {
var x = this.http.get<Employee[]>('http://dummy.restapiexample.com/api/v1/employees');
return x;
//alert(JSON.stringify(x)); This won't work because you need to first subscribe to the observable.
}

// Let's say there is a main function which calls your getEmployees function. So this is what you need to do

main() {
  this.getEmployees().subscribe(x => {
    alert(JSON.stringify(x));
  });
}
shobhit vaish
  • 951
  • 8
  • 22