Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 do not refresh view after array push in ngOnInit promise

I created a NativeScript app with angular 2, i have an array of objects that i expect to see in the frontend of the application. the behaviour is that if i push an object into the array directly inside the ngOnInit() it works, but if i create a promise in the ngOnInit() it doesn't 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
         });
     }
 }

the relative html is:

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

when the app starts i see only one push, but than i created a button that trigger a "console.log(JSON.stringify(this.stories));" and at that moment, when i tap the button, the ui seems to detects the changed array, and the other pushed object appears.

EDIT:

I created a more simple example in this thread: Angular 2: when i change a variable in a promise.than in ngOnInit the view doesn't refresh

like image 1000
Andrea Veronesi Avatar asked Aug 28 '16 23:08

Andrea Veronesi


1 Answers

The change detection is based on references, and pushing an element to an array will not trigger it. Try updating the reference like this:

this.stories.push(story);
this.stories = this.stories.slice();
like image 148
nickspoon Avatar answered Oct 16 '22 04:10

nickspoon