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

如何解决带有Firebase数据的Angular应用程序:为什么我看到上一页中的数据?

因此,我在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();
  }

与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();
  }

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

  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",00"}
  length: 4
  __proto__: Array(0)
  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","CFEB","MELE"]

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

解决方法

我认为问题出在这里:

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

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

ngOnDestroy() {
  this.txSubscription.unsubscribe();
}

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

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(...)
,

您在交易页面上获得2次结果。 valueChanges很可能从Firestore内存高速缓存中返回数据作为快速响应,然后从真实数据中读取。在您的情况下,当在首页上返回4行时会缓存它们,并从事务页面上的缓存中对其进行处理。

,

此问题可能是由于

this.afAuth.onAuthStateChanged()

触发两次。

代替检查每个组件上的auth状态。 您可以简单地在app.component.ts上订阅身份验证状态。如果用户未经身份验证或身份验证状态更改,它将重定向到登录页面,否则将重定向到home.page.ts

export class AppComponent {
  constructor(private readonly auth: AngularFireAuth,private router: Router) {
    this.auth.authState.subscribe(response => {
      console.log(response);
      if (response && response.uid) {
        this.router.navigate(['dashboard','home']); //Home page route
      } else {
        this.router.navigate(['auth','login']); //Login page route
      }
    },error => {
      this.auth.signOut();
      this.router.navigate(['auth','login']); //Login Page route
    });
  }
}

在home.component.ts和transaction.page.ts中,无需检查身份验证状态。

  • home.component.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.getRecentTransactions();
  }

  ngOnDestroy() {
    this.txSubscription.unsubscribe();
  }
  • 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','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.loadHomeData();
  }

  ngOnDestroy() {
    this.txSubscription.unsubscribe();
  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-