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

后端 未结 2 1824

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 in

相关标签:
2条回答
  • 2021-01-17 12:00

    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();
    
    0 讨论(0)
  • 2021-01-17 12:07
            setTimeout(function () {
                this.stories.push(story);
            }, 0);
    

    I had reall trouble with pushing into nested array, with almost random refresh results, till i stumped on this spec :

    Basically application state change can be caused by three things:

    • Events - click, submit, …

    • 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 ...

    0 讨论(0)
提交回复
热议问题