My goal is to retrieve data from a REST endpoint and then construct a List of instances to return. However, I'm facing an issue where the HTTP GET function returns an Observable method that always results in an empty list before populating it with data from the response.
Below is the code snippet:
public getUsers() {
let responseValue = this.http.get(this.utils.provideserviceURL('http://test.com/users'));
responseValue.toPromise()
.then(result => {
let usersList: User[] = [];
let jsonResult = result.json();
for (let temp of jsonResult) {
let tempUser = new User(jsonResult.id, jsonResult.username, jsonResult.password, jsonResult.firstName, jsonResult.lastName);
usersList.push(tempUser);
}
console.log(usersList);
return usersList;
})
.catch(err => {
// Error while fetching Users
console.log('Error');
});
}
The problem lies in the fact that the function initially returns undefined before displaying the console log with the correct data.
I am uncertain about the proper usage of the toPromise() method. If there's already a discussion on this topic, please guide me towards it or mark this question as a duplicate.