angular - Ionic 4每次进入都会刷新标签页

标签 angular typescript firebase angular-routing ionic4

我正在使用选项卡,每次重新进入页面时都无法刷新页面。我使用的是 ionic 4,所以无法使用 navController。

我已经使用 ionViewWillEnter() 在我的应用程序中显示数据库中的数据,它可以工作,但每次我转到另一个页面并返回到该页面时,它都会重复数据。 (例如,我正在显示来自 firebase 的 5 条数据。当我转到另一个页面并重新进入该页面时,它显示 10(重复相同的数据),然后是 15、20、25...等等)。

食物.page.html

<ion-list  *ngIf="showFood">
    <ion-row *ngFor='let FoodFruit of showTypeOfFood("fruit")'>
        <ion-col>
            <ion-card>
                <div class="card-title">{{FoodFruit.wtitle}}</div>
            </ion-card>
        </ion-col>
    </ion-row>
</ion-list>

食物.page.ts

ionViewWillEnter(){
    this.currentUser = this.afAuth.auth.currentUser;

    if(this.currentUser == null){
     this.showFood = false;
    }
    else{
      this.showPersonalFood();
    }
}

showPersonalFood(){
    this.afAuth.auth.onAuthStateChanged(
    (user)=>{
      if(user){
        this.showFood = true;

    this.afDatabase.object('foods/').snapshotChanges().subscribe(
      (action)=>{
            if(action.payload.val())
            {
              console.log(action.payload.val());
              let items: any = action.payload.val();
              items.forEach(
                (food) =>{
                  this.foods.push(food);
                }
              );
            }
            else
            {
              console.log("No Data");
            }
          });
      }
    }
  );

}
showTypeOfFood(type)
  {
    let items:any = [];
    this.foods.forEach((Food)=>{
      if(Food.wtype == type)
      {
        items.push(Food);

      }
    });
    return items;
    }

这里,showTypeOfFood 只是一个显示来自 firebase 的数据的函数。 所以,它完美地显示了食物标签页中的数据,但它只是不会刷新/清除缓存或删除以前的数据。我该如何实现这一点?

最佳答案

问题是 Ionic 不太适合刷新页面。如果你问 Ionic 创建者,这不是一个错误,而是一个功能......

但是他们有办法绕过这个:

“完全按照你的要求去做,但你不应该那样做”的方式

为您的页面提供一个每次进入时都会更改的属性(例如时间戳),以便 Ionic 被迫将其视为新页面来更新页面。

为什么你不应该这样做:

如果这样做,您的内存将会重载,并且您的应用可能会崩溃

“从技术上讲,您不刷新页面,只刷新数据,但它完成了工作”方式

首先,在 ionViewDidEnter() 中完成所有操作(这样当您真正进入页面时,所有操作都会完成)。

那么你必须:

  • 声明属性:
export class VisionnagePage implements OnInit{ 
    public YourVar = [];//you access it with this.YourVar
    constructor(){};
}
  • 进入页面时清空全局变量
  • 将项目放入此变量中。
  • 阅读它(就像您正在阅读 showTypeOfFood("fruit"))

关于angular - Ionic 4每次进入都会刷新标签页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56535284/

相关文章:

html - 为什么 [routerLink] 指令选择器定义为 :not(a)[routerLink]?

angularjs - 使用 Resharper 运行 AngularJS 测试

typescript - 将抽象类实现为类型

android - 从内部监听器中删除 Firestore 快照监听器

javascript - Angular2 应用优化

javascript - Angular carousel js 有时加载有时不加载

angular - router.navigate 不起作用

typescript - 狭窄的未知对象

javascript - 如何从数据库 firebase 获取推送 ID

javascript - 将变量推送到嵌套函数之外