首页 > 解决方案 > 从 firebase 数据库中获取用户数据并在 table.html 中显示

问题描述

我想从 firebase 的数据库中获取用户数据并在 HTML 表中显示该数据。

我应该导入一些库吗?我的 .ts 文件中究竟应该包含什么?我需要一个关于如何做到这一点的分步程序。我是初学者,刚刚学习 Angular。在此处输入图像描述

我不知道我到底在做什么

标签: angulartypescriptfirebase

解决方案


我不确定你安装了什么来从 FireBase 获取数据,但看看我假设你使用AngularFire的代码。

您应该按照这个快速安装步骤设置基本模式,以将文档作为Observable读取并在组件模板中使用其数据。

在你的 student-user.component.ts 文件中:

  users: Observable<any>;

  constructor(private db: AngularFirestore) {
  }

  ngOnInit(){
      this.users = db.collection('users').valueChanges();
  }

在您的 HTML 模板中,您打开 observable 并使用*ngFor指令循环users并根据提供的数据创建元素:

<p *ngFor="let user of users | async"> {{user.userName}} </p>


或者,您可以在 ts 文件中的某处订阅 Observable 以解包数据,但您应该在此期间取消订阅ngOnDestroy()以避免内存泄漏

 this.subscription = this.users.subscribe(console.log);

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

推荐阅读