Angular 2 don't refresh view after clicking array in ngOnInit prom

I created a NativeScript application with angular 2, I have an array of objects that I expect to see in the frontend of the application. the behavior is that if I push an object into an array directly inside ngOnInit (), it works, but if I create a promise in ngOnInit (), this will not work. here is the code:

export class DashboardComponent { stories: Story[] = []; pushArray() { let story:Story = new Story(1,1,"ASD", "pushed"); this.stories.push(story); } ngOnInit() { this.pushArray(); //this is shown var promise = new Promise((resolve)=>{ resolve(42); console.log("promise hit"); }); promise.then(x=> { this.pushArray(); //this is NOT shown }); } } 

relative html:

 <Label *ngFor="let story of stories" [text]='story.message'></Label> 

when the application starts, I see only one click, but I created a button that launches "console.log (JSON.stringify (this.stories)); and at that moment, when I click the button, ui seems to detect a changed array. and another pushed object appears.

EDIT:

I created a simpler example in this thread: Angular 2: when I change a variable in a promise. in ngOnInit view is not updated

+12
angular es6-promise nativescript angular2-nativescript
source share
2 answers

Change detection is based on links, and pushing an element into an array does not call it. Try updating the link as follows:

 this.stories.push(story); this.stories = this.stories.slice(); 
+19
source share
  setTimeout(function () { this.stories.push(story); }, 0); 

I really had problems loading into a nested array with almost random update results, until I was puzzled by this specification:

Basically, an application state change can be caused by three reasons:

  • Events - click, send, ...

  • XHR - fetching data from a remote server

  • Timers - setTimeout (), setInterval ()

( https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html#what-causes-change )

So I tried setTimeout, and miraculously it worked ...

-one
source share

All Articles