带有 Firebase 数据的 Angular 应用:为什么我会看到上一页的数据?

vdv*_*xel 5 javascript firebase typescript angular google-cloud-firestore

因此,我在 Firebase 上托管了一个 Angular 9 应用程序,并使用 Firestore 存储数据。我有一个看起来很简单的问题,但我无法理解它为什么会发生。我已经对应用程序进行了大量简化,以找到导致此问题的根本原因,并将尝试在下面尽可能详细地解释该问题。

该应用程序:我有 2 个页面,一个主页和一个交易页面。两个页面都从同一个 Firebase 集合“交易”中读取。但是,在主页上,我想显示 4 个最近的交易(按日期排序,降序),而在交易页面上,我想显示 10 个最有利可图的交易(按金额排序,降序)。目前,我只是将数据记录到控制台进行调试。在记录数据之前,我还对其进行了轻微的操作(参见下面的代码)。

问题:当我在主页上开始时,我可以在控制台中按预期看到我最近的 4 个交易。但是,当我转到“交易”页面时,它会再次在控制台中记录 4 个最近的交易,这些交易应该只显示在主页上。大约一秒钟后,它会显示预期的 10 个最有利可图的交易。

代码:这是我的 home.page.ts 代码:

  txSubscription: Subscription;

  constructor(
    public afAuth: AngularFireAuth,
    private readonly firestore: AngularFirestore
  ) { }

  // Function to get the 4 most recent transactions
  async getRecentTransactions() {
    this.txSubscription = this.firestore
      .collection('transactions', ref => ref.orderBy('date', 'desc').limit(4))
      .valueChanges()
      .subscribe(rows => {
        this.recentTransactions = [];

        rows.forEach(row => {
          let jsonData = {};
          jsonData['ticker'] = (row['ticker'].length <= 10 ? row['ticker'] : row['ticker'].substring(0, 10) + '...');
          jsonData['date'] = formatDate(row['date'].toDate(), 'dd/MM/y', 'en');
    
          jsonData['amount'] = prefix + formatNumber(row['netAmount'], 'be', '1.2-2');
    
          this.recentTransactions.push(jsonData);
        })

        console.log("home page", this.recentTransactions);
      })
  }

  ngOnInit() {
    this.afAuth.onAuthStateChanged(() => {
      this.getRecentTransactions();
    })
  }

  ngOnDestroy() {
    this.txSubscription.unsubscribe();
  }
Run Code Online (Sandbox Code Playgroud)

和 transaction.page.ts 的代码非常相似:

  txSubscription: Subscription;

  constructor(
    public afAuth: AngularFireAuth,
    private readonly firestore: AngularFirestore
  ) { }

  // Function to load the data for the home page
  loadHomeData() {
    this.txSubscription = this.firestore
      .collection('transactions', ref => ref.orderBy('profitEur', 'desc').limit(10))
      .valueChanges()
      .subscribe(rows => {
        this.resultRows = [];

        rows.forEach(row => {
          this.resultRows.push(row['ticker'].slice(0, 8));
        });

        console.log("transaction page", this.resultRows);
      })
  }

  ngOnInit() {
    this.afAuth.onAuthStateChanged(() => {
      this.loadHomeData();
    })
  }

  ngOnDestroy() {
    this.txSubscription.unsubscribe();
  }
Run Code Online (Sandbox Code Playgroud)

结果:这是每一步输出到控制台的内容

  1. 我在主页上打开应用程序(如预期的 4 行):
home page (4) [{…}, {…}, {…}, {…}]
  0: {ticker: "BAR", date: "21/07/2020", amount: "- € 1 086,10"}
  1: {ticker: "ASL C340.0...", date: "18/07/2020", amount: "€ 0,00"}
  2: {ticker: "ASL C340.0...", date: "14/07/2020", amount: "- € 750,85"}
  3: {ticker: "TUI C7.00 ...", date: "20/06/2020", amount: "€ 0,00"}
  length: 4
  __proto__: Array(0)
Run Code Online (Sandbox Code Playgroud)
  1. 我导航到交易页面:
transaction page (4) ["TUI C7.0", "ASL C340", "BAR", "ASL C340"]

transaction page (10) ["ASL C240", "ASL C232", "REC", "ASL C270", "ASL C310", "ASML", "ASL P220", "BAR", "CFEB", "MELE"]
Run Code Online (Sandbox Code Playgroud)

为什么在导航到主页时,控制台中的主页再次显示相同的 4 行?

Rob*_*hof 0

我认为问题出在这里:

loadHomeData() {
  this.txSubscription = this.firestore
  ...
  .subscribe(rows => {
    ...
  })
}

ngOnInit() {
  this.afAuth.onAuthStateChanged(() => {
    this.loadHomeData();
  })
}

ngOnDestroy() {
  this.txSubscription.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)

您取消订阅是正确的。但是,看看 onAuthStateChanged 再次触发时会发生什么。您的第一个订阅已丢失,并且无法取消订阅。我认为使用switchmap运算符 ononAuthStateChanged可以解决您的问题。像这样的东西:

this.subscription = this.af.authState.pipe(
  switchMap(auth => {
    if(auth !== null && auth !== undefined){
      return   this.firestore.collection('transactions', ref => ref.orderBy('profitEur', 'desc').limit(10)).valueChanges())
    } else{
      throw "Not loggedin";
    }
).subscribe(...)
Run Code Online (Sandbox Code Playgroud)