数组推入ngOnInit Promise后,Angular 2不刷新视图 [英] Angular 2 do not refresh view after array push in ngOnInit promise
问题描述
我创建了一个带有角度2的NativeScript应用程序,我有一个对象数组,希望在应用程序的前端看到它们.行为是,如果我直接将对象推入ngOnInit()内部的数组中,它将起作用,但是如果我在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
});
}
}
相对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.
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();
这篇关于数组推入ngOnInit Promise后,Angular 2不刷新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!