[英]Ionic2 ngFor in view not updating
我的應用程序中有元素列表,可以在* ngFor中將它們打印出來。 恢復應用程序后,我會通過執行http-Request調用一個方法從服務器加載新元素。 在此方法內部,我將項目設置為數組的元素。
但是,數組不會在視圖中更新。 如果我執行“強制刷新”(我在其中調用相同的方法),則視圖中的元素將更新。
我嘗試包裝我的代碼部分,該部分覆蓋ngZone的.run()
或setTimeout()
的舊數組,但沒有任何效果。 還嘗試了ChangeDetectorRef
,也沒有成功。
現在我沒有任何想法...
到目前為止,這是我嘗試過的:
this.zone.run(() =>{
this.posts = posts; // "posts" is the array of elements i got from http-request
// "this.posts" the array for the view
});
並且
setTimeout(() => {
this.posts = posts;
}, 10);
和
this.posts = posts;
this.changedetectorRef.detectChanges(); //also tried markForCheck()
我的密碼:
視圖:
<ion-item-sliding *ngFor="let post of posts" >
<ion-item>
<p>{{post.newdistance}}</p>
</ion-item>
</ion-item-sliding>
對應的.ts文件:
loadPosts() {
let loading = this.loadingController.create({
content: "Einen Moment bitte...",
spinner: "crescent"
});
loading.present();
this.postsService.getPostsFromServer().then(posts => {
posts.forEach((post, index) => {
this.geolocationService.getDistance(post.latitude, post.longitude).then(distance => {
post.newdistance = distance;
});
});
this.posts = posts; // <---- what to do here ???
loading.dismiss();
})
.catch(() => {
loading.dismiss();
});
}
請幫我!
更新
當我發出警報並將舊的發布值與新的發布值進行比較時,兩者都會更新。 問題絕對是沒有更新的觀點
更新2
我注意到,當我在視圖上添加一個按鈕並調用相同的功能時,該視圖也會被更新...當我恢復該應用程序時它不會被更新...
this.posts = posts;
您的部分代碼可能在
this.geolocationService.getDistance(post.latitude, post.longitude).then(distance => {
post.newdistance = distance;
});
我說“ 可能在 ” 之前 ,因為這是一個承諾,您不能確定它何時會確切返回。 因此, 在將posts
分配給this.posts
之后 ,將設置newdistance值。
解決此問題的最好方法是將您的promise方法鏈接在一起,而不是並行執行。
另一種(更簡單的方法)是僅在獲得newdistance值之后才將每個post
都推送到this.posts
。 請記住 ,您應該使用新數組來推送帖子,如下所示:
//at the top of you page declare a new postsArray variable
postsArray = [];
this.postsService.getPostsFromServer().then(posts => {
posts.forEach((post, index) => {
this.geolocationService.getDistance(post.latitude, post.longitude).then(distance => {
post.newdistance = distance;
// Here we push the new post into the posts array
this.postsArray.push(post);
});
});
loading.dismiss();
})
.catch(() => {
loading.dismiss();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.