Angular 2 在 ngOnInit 承诺中推送数组后不刷新视图 [英] Angular 2 do not refresh view after array push in ngOnInit promise

查看:20
本文介绍了Angular 2 在 ngOnInit 承诺中推送数组后不刷新视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有 angular 2 的 NativeScript 应用程序,我有一个我希望在应用程序前端看到的对象数组.行为是,如果我直接在 ngOnInit() 内部将一个对象推入数组,它会起作用,但是如果我在 ngOnInit() 中创建一个承诺,它就不起作用.这是代码:

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
         });
     }
 }

相对的html是:

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

当应用程序启动时,我只看到一个按钮,但我创建了一个触发console.log(JSON.stringify(this.stories));"的按钮在那一刻,当我点击按钮时,ui 似乎检测到更改后的数组,并出现另一个推送对象.

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.

我在此线程中创建了一个更简单的示例:Angular 2:当我在 promise.than 中更改一个变量时,视图不会刷新

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

推荐答案

变更检测基于引用,将元素推送到数组不会触发它.尝试像这样更新参考:

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

这篇关于Angular 2 在 ngOnInit 承诺中推送数组后不刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆