I am making angular application and where i am having an empty array like,
users: any = [];
Then i am making a service call in ngOn
You can store data in array without loop also.
ngOnInit() {
//Getting the data from json
this.httpClient.get('https://api.myjson.com/bins/n5p2m').subscribe((response: any) => {
this.users.push(...response.data)
console.log("users array", this.users);
})
}
Had forked you Stackblitz Demo
If you want to manipulate your data after the HTTP Client response, you can actually do so by playing with the RxJS operators. After those methods inside the pipe, when you subscribe to its final value, it will directly render to your template.
this.httpClient
.get('https://api.myjson.com/bins/n5p2m')
.pipe(
map(response => response.data),
tap(users => console.log("users array", users)) // users array [Object, Object, Object]
)
.subscribe(users => this.users = users);
If you don't want to use the RxJS Operators, you can still manipulate it after you had subscribed to its final value and perform your manual data manipulation
There's no need to perform the .forEach() to store the array of objects from your response.data as Angular had already perform it for you. So whenever you assign it as
this.users = response.data
it will store your Array of Objects[Object, Object, Object]
this.httpClient
.get('https://api.myjson.com/bins/n5p2m')
.subscribe(response => this.users = response.data); // This will directly store your response data in an array of objects.
Angular can use Promises and Observables to handle asynchronous operations such as this http get request. There's lots of information on this concept and here is a good starting point: Promise vs Observable
To further elaborate, you could wrap the http get request in a method that returns an Observable, and then subscribe to that method and wait for it to return a result before executing the log statement.