You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无需点击HTML按钮,在Angular页面加载时自动执行TypeScript函数

ngOnInit工作原理与自动执行函数实现

ngOnInit 是Angular内置的组件生命周期钩子,会在组件初始化完成、输入属性绑定完成后自动触发,不需要绑定任何点击事件就能自动执行,完全符合你页面打开自动加载数据的需求。

你当前代码未正常执行的核心原因是userId变量仅做了声明没有实际赋值,调用fetchBookings时无法定位到对应的Firestore文档,按以下方案修改即可:

1. 修复TypeScript逻辑

export class MyReservationsPage implements OnInit {
  user: any;
  userId: string;
  storedData: any = [];

  constructor(private auth: AuthService, private afs: AngularFirestore) {}

  ngOnInit() {
    // 先从登录服务获取当前用户ID,拿到后再调用数据拉取方法
    this.auth.currentUser.subscribe(user => {
      if(user) {
        this.userId = user.uid;
        this.fetchBookings();
      }
    })
  }

  fetchBookings() {
    this.afs
      .collection('user')
      .doc(this.userId)
      .collection('BookingHistory')
      .get()
      .subscribe((querySnapshot) => {
        this.storedData = querySnapshot.docs.map((e) => {
          return {
            bookingDate: e.data()['Merge'],
          };
        });
      });
  }
}

2. 修复HTML标签问题

你现有HTML中遗漏了ion-前缀,会导致布局异常,修改后代码如下:

<ion-content>
    <ion-grid>
        <ion-row *ngFor="let data of storedData">
            <ion-col *ngFor="let value of data.bookingDate">
                <ion-row>{{value.Date}}</ion-row>
                <ion-row>{{value.Time}}</ion-row>
                <ion-row>{{value.BookedAt.toDate() | date:'medium'}}</ion-row>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

可选:适配Ionic页面生命周期的自动执行方案

如果你需要每次进入页面都刷新预订数据,可以使用Ionic专属的ionViewWillEnter钩子,该钩子会在每次页面即将展示时自动触发:

import { IonViewWillEnter } from '@ionic/angular';

export class MyReservationsPage implements OnInit, IonViewWillEnter {
  // 原有变量声明保持不变

  ionViewWillEnter() {
    // 此处逻辑每次进入页面都会自动执行
    if(this.userId) {
      this.fetchBookings();
    }
  }

  // 原有其他方法保持不变
}

内容的提问来源于stack exchange,提问作者Victor Nem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 03:15:10