繁体   English   中英

Ionic2 ngFor视图未更新

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM