I'm aware this might be a repeated question, but I haven't come across a straightforward answer yet, so here it goes.
Below is the code snippet in question:
fetchData() {
let dataArray: Array<any> = [, , ,];
this.prepareDataRequest().subscribe(data => {
this.dataArray[0] = JSON.parse(JSON.stringify(data["results"]));
this.dataArray[1] = Object.keys(JSON.parse(JSON.stringify(data["results"]))).length;
console.log(this.dataArray[0]);
},
err => {
this.dataArray[2] = `Error --> Status: ${err.status}, Message: ${err.statusText}`;
});
return this.dataArray;
}
prepareDataRequest() {
const dataUrl = 'https://randomuser.me/api/?results=10&inc=gender,name,nat,email,phone,id';
return this.http.get(dataUrl);
}
The console.log(this.dataArray[0]);
line works correctly, however, the return statement appears empty. This issue seems to occur because return this.dataArray;
is executed before fetching the items.
How can I resolve this? Is there a simple way to ensure everything is stored before returning? Or am I approaching this incorrectly (probably xD)?
I've experimented with async methods, but being relatively new to this, the results weren't satisfactory.