Mahmoud Tohmaz
Mahmoud Tohmaz

Reputation: 9

Angular 2 ngFor won't update when object array changes

I'm working on getting a json object array using an http get request. Currently, I have a list-view.component that calls a function, getEvents() in my event.service component. That function returns Promise, which represents the object array. It successfully returns the updated array to list-view.component, but for some reason, when I try to print out the array on console, it doesn't show the changes.

list-view.component.ts

this.eventService.getEvents(lat, lon, range, s).then(events => this.eventsList = events);
console.log(this.eventsList);

event.service.ts

getEvents(lat: number, lon: number, radius: number, s: string): Promise<Event[]> {
    return this.http.get(this.eventsUrl + "?s=" + s +"&radius=" + radius + "&lat=" + lat + "&lon=" + lon)
        .toPromise()
        .then(response => response.json() as Event[])
        .catch(this.handleError);
  }

If I try to print the array in the .then method, like below, it prints it correctly.

this.eventService.getEvents(lat, lon, range, s).then(events => console.log(events));

How come, when I try to print it after the this.eventService.getEvents() call, it doesn't have the new changes?

Upvotes: 0

Views: 2279

Answers (2)

Ivar Reukers
Ivar Reukers

Reputation: 7719

Promise.then() is an async method, which means that the value returned can't be used outside of it. Everything you need to do with your events returned by your promise should be put within the .then().

This if for the reason that your method is calling .then(), it will, but the Promise hasn't yet been resolved and the value hasn't yet been set.

Then your method will continue and print your console.log(). Some time (milli/nano-seconds) later, your async operation finished.

You could see it something like this:

fun test() {
   setTimeout(() => {
     console.log('Async operation ended');
    }, 2000);

   console.log('Normal operation ended');
}

which is basically what you created. Your method will call the setTimeout(), and immediately continue with the console.log without waiting for the timeout to finish.

To print the

Async operation ended

Before, you should include it within your setTimeout() (in your case your then())

fun test() {
   setTimeout(() => {
     console.log('Async operation ended');
     console.log('Normal operation ended');
    }, 2000);

}

Upvotes: 0

David
David

Reputation: 7507

I'd say thats because the console.logstatement is executed before the promise returns. It works with .then because it`s executed when the promise returns.

Hope this helps.

Upvotes: 1

Related Questions