javascript - Ionic 选项卡在数据加载之前完成显示

标签 javascript angular ionic-framework

我正在尝试为代金券应用创建一个收藏夹部分。我检索当前用户最喜欢的优惠券并在 HTML 中使用 ngFor 显示它们。但是,我第一次打开收藏夹选项卡时,优惠券不显示。但是,如果我转到另一个选项卡然后返回,它会显示。在我完成一次之后,即使我转到其他选项卡并返回,它也会立即继续显示。只有在我重新启动我的应用程序后,问题才会再次出现。我想知道如何确保凭证第一时间显示。

我将收藏夹凭证的提取放在 ionViewWillEnter() 函数中。

TS

ionViewWillEnter() {
    this.http.get('http://xxxx.com/api/users').subscribe((data: any)=>{
      this.users=data["data"]
    })

    this.authService.user().subscribe(
      user => {
        this.user = user;
      } 
    );
    this.getFavourites()
}
getFavourites(){
    var i;
    for(i=0; i<this.users.length;i++){ //Check all users for current user
      if(this.users[i].first_name === this.user.first_name){
        this.favourites = this.users[i].getfavourites //extract array of favourited vouchers
      }
    }
}

HTML

<ion-list>
    <ion-item lines="none"  *ngFor="let favourite of favourites">
      <ion-label> 
        <a routerLink="/details" routerDirection="forward" (click)="openDetails(favourite)"><img class="voucher_image" `enter code here`src='http://xxxx.com/imgs/vouchers/{{favourite.image}}'></a>
      </ion-label>
    </ion-item>
 </ion-list>

更新:基于 Sergey 解决方案的固定代码

TS

ngOnInit(){
  this.ionViewWillEnter()
 })
}

async ionViewWillEnter() {
   this.http.get('http://wuiske.com/api/usersall').subscribe((data: any)=>{
   this.users=data
  })
   this.user = await this.authService.user().toPromise();
   this.getFavourites()
}

最佳答案

问题是您的 getFavorites() 方法依赖于您尝试以异步方式并行获取的一些数据源,因此一旦它们完成执行,您就已经调用了 getFavorites()。基本上意味着您在 ionViewWillEnter 中的两个异步调用在您调用 getFavorites() 之后完成。

看起来你在代码中使用了 Observables,所以你应该能够做这样的事情:

async ionViewWillEnter() {

    this.users = await this.http.get('http://xxxx.com/api/users').toPromise();
    this.user = await this.authService.user().toPromise();
    this.getFavourites()

}

此外,此生命周期 Hook (ionViewWillEnter) 不是启动数据获取调用的最佳选择,因为它源自过渡动画,而不是在类实例化时。理想情况下,您希望使用 ngOnInit() 或什至从构造方法中请求数据。

关于javascript - Ionic 选项卡在数据加载之前完成显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57114640/

相关文章:

angular - 传单 divIcon 未以 Angular 显示在 map 上

angular - 如何检查是否在组件上触发了变更检测

javascript - 无法将 {{> loginButtons}} 与 Meteor 和 Ionic 一起使用

php - 如何从 PHP 返回到 Ionic Controller?

java - 使用 Hmac SHA1 签署 HTTP 请求

javascript - 我在菜单项上使用 react Hook 。我的第一次点击没有做任何事情,随后的点击按预期工作

html - 带有 PrimeNG 的 Angular 2 嵌套模态对话框不起作用

javascript - Angular 绑定(bind)错误

javascript - TypeScript:在代理中定义动态属性

javascript - 试图让我的输出显示在正文部分,格式包括页眉、正文(带背景)和页脚