首页 > 解决方案 > (Angularfire) 从具有 id 的 firebase 数据库中检索特定数据

问题描述

我正在尝试使用 angular 和 firebase 创建一个“博客”。我的第一个 Angular 和 Firebase 项目都做得很好。

我制作了加载所有条目的首页,然后添加了一个“阅读更多...”超链接到特定文章的路径以及条目的 ID。这是HTML:

<div style="background-color:white" class=" contenedorBlog">

    <h1 style="padding-top:100px;" class="text-center mb-4">Pizarrón</h1>

    <div *ngFor="let item of items" style="padding:40px" class="rounded">
      <h2> {{item.title}} </h2>
      <p>Date: {{ item.systemDate }}</p>
      <div class="content" [innerHTML]="item.content"></div>
      <a [routerLink]="['/article', item.id]">Read more...</a>
    </div>

  </div>

这是文章组件的 HTML:

<div style="background-color:white" class=" contenedorBlog">

    <div style="padding:40px" class="rounded">
      <h2> {{items.title}} </h2>
      <p>Fecha: {{ items.systemDate }}</p>
      <div class="content" [innerHTML]="items.content"></div>
    </div>

  </div>

我试图弄清楚如何调用路径上具有 id 的特定对象(article/:id)。

这就是我到目前为止所拥有的(article.component.ts)

export class ArticlesComponent implements OnInit {

   items:any;

   constructor(private blogService: UploadService, private route: ActivatedRoute) {
      this.route.params.subscribe(params=> {
      this.items=this.blogService.getObjectById(params['id']);
   });
   }

   ngOnInit() {
   }

}

问题是……我不知道下一步该做什么。我在一个服务中调用一个函数,我只想检索包含路径上的 id 的对象。

getObjectById(id) {
    ///Help
}

非常感谢你,并为我的英语不太好感到抱歉。

标签: angularfirebaseangularfire

解决方案


改变:

this.items=this.blogService.getObjectById(params['id']);

到:

this.blogService.getObjectById(params['id']).subscribe( i => {
        this.items = i;
    })

它们在 getObjectById(id) 中:

getObjectById(id) { 
     return this.afs.collection('collectionName').doc(id).valueChanges()
}

如果您只想要一次值,请在“.subscribe”之前使用“.take(1)”

如果您不想看到“未定义”错误,还需要将 *ngIf="items" 放在显示“items”的元素中。


推荐阅读