Angular 2 do not refresh view after array push in ngOnInit promise
Asked 07 September, 2021
Viewed 2.3K times
  • 52
Votes

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

3 Answer