(Angularfire)使用id从firebase数据库中检索特定数据

时间:2018-06-01 00:15:33

标签: angular firebase angularfire

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

我创建了加载所有条目的首页,然后添加了一个“read more ...”超链接到特定文章的路径加上条目的id。 这是HTML:

$ who
zack     :0           2018-05-30 17:37 (:0)

这是文章组件的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>

我正在试图弄清楚如何调用路线上具有id的特定对象(文章/:id)。

这是我到目前为止(article.component.ts)

<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的对象。

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() {
   }

}

非常感谢,对不起,我的英语不是很好。

2 个答案:

答案 0 :(得分:1)

在构造函数中定义一个AngularFirestore变量,然后在函数中使用它,如下所示:

constructor(private afs: AngularFirestore){
  this.route.params.subscribe(params=> {
    this.getObjectById(params['id']);
  });
}

getObjectById(id) {
    return this.afs.collection('collection_name')
      .doc(id)
      .ref;
}

然后您可以在组件上使用该功能,如:

this.blogService.getObjectById(params['id']).get().then(res => {
    console.log(res)
})

答案 1 :(得分:1)

变化:

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

如果您只想使用一次值,请使用&#34; .take(1)&#34;在&#34; .subscribe&#34;

之前

你还需要输入* ngIf =&#34; items&#34;在您展示&#34;项目&#34;的元素中如果你不想看到&#34; undefined&#34;错误。

相关问题