3

I am making angular application and where i am having an empty array like,

  users: any = [];

Then i am making a service call in ngOnInit to store the data into users array like,

  ngOnInit() {

    //Getting the data from json
    this.httpClient.get('https://api.myjson.com/bins/n5p2m').subscribe((response: any) => {
      console.log("response", response.data);
      response.data.forEach(element => {
        //Pusing the data to users array
        this.users.push(element);
      });
    })

    //Trying to get the complete array after push of the element from the service response data
    console.log("users array", this.users);
    //But it shows empty array
  }

But i am unable to get the data in console.log("users array", this.users); as because the service call makes a delay..

How to push the data into this.users and when we call outside of the service it should have the filled data and not empty as like now..

Also made a working stackblitz regarding it https://stackblitz.com/edit/angular-q3yphw

Please see the console which has current result..

Current result in console.log("users array", this.users); is empty array [].

So i am expecting the following result in console.log("users array", this.users); outside the service and inside ngOnInit,

[
{"id":1,"value":"User One"},
{"id":2,"value":"User Two"},
{"id":3,"value":"User Three"}
]

As i am new in angular kindly help me to achieve the expected result..

Maniraj Murugan
  • 8,868
  • 20
  • 67
  • 116

3 Answers3

6

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.

Result

KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • ```this.httpClient .get('https://api.myjson.com/bins/n5p2m') .subscribe((response:any) => this.users = response.data); console.log("users array", this.users);``` This one still shows empty array.. – Maniraj Murugan Dec 08 '18 at 06:42
  • My need is outside the service call i need to get the filled data in ```this.users```.. – Maniraj Murugan Dec 08 '18 at 06:44
  • Here for example i have shown like this but in my real application i need to loop through the array and to push the element to it and get the final result.. – Maniraj Murugan Dec 08 '18 at 06:51
  • Whenever you want to fetch something from an HTTP, you need to subscribe to its value inside and perform your data manipulation there. Had updated the forked Stackblitz demo link i had shared with a Service integration and with using Subject observable as well – KShewengger Dec 08 '18 at 06:55
  • Had also added a filter function inside the .subscribe and angular was able to render the result on the template – KShewengger Dec 08 '18 at 06:57
  • 1
    Thanks.., but also keep the ```RxJS operators``` stackblitz.. I think that is the best solution to handle.. – Maniraj Murugan Dec 08 '18 at 07:02
  • @undefined thanks, had updated the Stackblitz utilizing the rxjs operators. Added 2 methods depends on your preferences both will emit the same value. Check the app.service.ts – KShewengger Dec 08 '18 at 08:04
3

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);  
  })            
}
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
0

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.

Derek
  • 126
  • 1
  • 7