In my Angular application, I have an empty array defined as follows:
users: any = [];
Within the ngOnInit
lifecycle hook, I make a service call to fetch data and store it in the users
array like so:
ngOnInit() {
//Fetching data from a JSON endpoint
this.httpClient.get('https://api.myjson.com/bins/n5p2m').subscribe((response: any) => {
console.log("response", response.data);
response.data.forEach(element => {
//Pushing the element data into the users array
this.users.push(element);
});
})
//Attempting to log the complete array after pushing elements from the service response data
console.log("users array", this.users);
//However, it shows an empty array at this point
}
I am facing an issue where the data is not available in
console.log("users array", this.users);
due to delays caused by the service call.
My goal is to populate this.users
with data that can be accessed outside of the service call and within the ngOnInit
function.
To illustrate the problem, I have created a working example on StackBlitz: https://stackblitz.com/edit/angular-q3yphw
Please refer to the console logs for the current results.
The current output in
console.log("users array", this.users);
is an empty array [].
My desired outcome when logging
console.log("users array", this.users);
both inside and outside of the service call in ngOnInit
is as follows:
[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]
As a newcomer to Angular, I would appreciate guidance on achieving the expected result.