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

坚强是说给别人听的谎言 提交于 2019-12-01 15:14:10

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();
        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 ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!