首页 > 解决方案 > 从 Angular 列表中获取所选项目

问题描述

我的 HTML 页面上显示了一个元素列表。对于选择的任何元素,我希望从 firebase 数据库中检索相应的数据。这是我如何在 HTML 页面上显示列表的代码。这些项目是从 firebase 检索的。

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

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

</div>

routerLink="records" ,Records.html 是我想显示相应数据的地方。Records 是一个 html 页面,其中...基于所选的“年份”,应动态加载数据。 HTML 页面上显示的项目 Firebase 数据库中的数据

标签: htmlangular

解决方案


我会使用两项服务

一个用于您的 http 调用(apiService),另一个用于将数据存储在您的应用程序中(在这种情况下dataService

在你的实际ts

years:any[] = []

//you can trigger that with ngOnInit or other events
this.apiService.getYears.subscribe(
  data => {
    this.dataService.setYears(data)
    this.years = this.dataService.getYears();
  }
)

在您的 html 中(不再async只是数据)

<div class="list-group " *ngFor="let year of years | async">
  <a [routerLink]="['records/'+ year.key]" routerLinkActive="active">
    <mdb-icon fas icon="table" class="mr-3"></mdb-icon>{{year.key}}</a>
</div>

然后在你的记录组件中

year:any = undefined

//check for ActivatedRoute.params for retrieving the key (here `yearKey`) in your url

ngOnInit(){
  if (!(this.year = this.dataService.getYear(yearKey)))
    this.apiService.getYear(yearKey).subscribe(
      data => this.year = data
    )
}

参考

服务


推荐阅读