【问题标题】:Get and display data from Firebase in Angular在 Angular 中从 Firebase 获取和显示数据
【发布时间】:2020-03-06 09:13:33
【问题描述】:

我在 Firebase 中有一些记录,我想在我的 HTML 页面上显示这些记录。我附上了数据库的结构。 现在,我想以数组的形式显示年份(可点击)。在选择特定年份时,我希望在我的代码中检索相应的记录。

我尝试检索年份,但无法在页面上显示它们。我尝试了一个静态数组,因为 years=["1999","1994"] 有效。只有数据库中的数据没有被检索和显示。

<div class="list-group " *ngFor="let year of years">

    <a routerLink="records"  routerLinkActive="active" >
        <mdb-icon fas icon="table" class="mr-3"></mdb-icon>{{year}}</a>

</div>
export class NavigationComponent implements OnInit {
  @ViewChild('sidenav', {static: true}) sidenav: ElementRef;

  //years = ['1999', '2004', '2019'];
  clicked: boolean;
  resizedImage: Blob;

  years:AngularFireList<any[]>;
  // TODO: Need to fix the click effect of years





  constructor(af:AngularFireDatabase,
    private router: Router,

    //private userService: UserService
    //private ng2ImgMax: Ng2ImgMaxService
  ) {
    this.clicked = this.clicked === undefined ? false : true;
    this.years=af.list('/years/Akhilesh');}

那是打字稿代码^

【问题讨论】:

  • 不要添加代码图片,而是用实际编写的代码替换它们。人们喜欢能够将问题复制并粘贴到他们的本地计算机中,以模拟您面临的问题。
  • @TheFabio 抱歉..我现在已经编写了实际代码
  • console.log(this.years) 返回什么?

标签: angular typescript firebase firebase-realtime-database angularfire2


【解决方案1】:

您的代码中存在多个问题。

首先,由于您正在从使用静态数组转移到从数据库调用,您现在必须使用Observable,这将影响您的模板——您需要通过| async 进行管道传输。

(为了演示,我只是在示例中输出 JSON,您需要根据实际对象结构进行调整):

<div class="list-group" *ngFor="let year of years | async">
  {{ year | json }}
</div>

如果您需要更多关于这里发生的事情,请参阅this part of the Angular Tour of Heros tutorial

接下来,您的years 声明需要调整:

years: Observable<any>;

(理想情况下,您应该使用 Finnish Notation 来命名 Observable,但为了与您的代码保持一致,我将省略它)。

当然,如果您还没有导入它,您还需要:

import { Observable } from 'rxjs';

最后,仅存储AngularFireList 对象是不够的,您必须实际订阅更改。在这种情况下,我将使用snapshotChanges,它提供了包括键在内的完整结构,但您也可以根据需要查看valueChanges。 (要访问“1994”之类的键,您需要在模板中使用year.keysnapshotChanges)。

    this.years=af.list('/years/Akhilesh').snapshotChanges();

我建议您仔细查看 AngularFire 文档中的 example

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-06-10
    • 2021-06-16
    • 2019-05-10
    • 2021-12-31
    相关资源
    最近更新 更多