在Angular 6中检索并显示Firestore文档

时间:2018-08-23 20:15:27

标签: angular firebase google-cloud-firestore

这是Angular 6和Firestore项目。我试图从Firestore检索单个文档,并将其值显示在组件模板中。

此代码有效。

article-detail.component.ts

export class ArticleDetailComponent {
  articlesCollection: AngularFirestoreCollection<Article>;
  articles: Observable<Article[]>;
  article: any;
  id: any = 1a3c;

  constructor (private afs: AngularFirestore) {
      this.articlesCollection = this.afs.collection('articles');
      this.articles = this.articlesCollection.valueChanges();

      #### RETRIEVE INDIVIDUAL DOCUMENT HERE #### 
      this.articlesCollection.doc(`${this.id}`).ref.get().then((doc) => {
        this.article = doc.data();
      });
  }

article-detail.component.html中,显示如下详细信息:

{{ article.title }}

{{ article.subtitle }}

{{ article.date }}

2 个答案:

答案 0 :(得分:2)

这是一种检索和显示角度的Firestore文档的方法。

article-detail.component.ts

export class ArticleDetailComponent {
  articlesCollection: AngularFirestoreCollection<Article>;
  articles: Observable<Article[]>;
  article: any;
  id: any = 1a3c;

  constructor (private afs: AngularFirestore) {
      this.articlesCollection = this.afs.collection('articles');
      this.articles = this.articlesCollection.valueChanges();

      #### RETRIEVE INDIVIDUAL DOCUMENT HERE #### 
      this.articlesCollection.doc(`${this.id}`).ref.get().then((doc) => {
        this.article = doc.data();
      });
  }

article-detail.component.html中,显示如下详细信息:

{{ article.title }}

{{ article.subtitle }}

{{ article.date }}

答案 1 :(得分:0)

是的,您应该获取所有值。

真的有字幕和日期吗?订阅ngOnInit中的this.article并打印到控制台进行检查。如果您在控制台中看到它,则可能是更改检测问题。

尝试在1秒钟后或收到数据后在setTimeout中运行手动更改检测。只是看看这是否是问题所在。

constructor(private cd: ChangeDetectorRef) {}

ngOnInit(){
   this.article.subscribe(data=> {
     console.log(data);
     this.cd.detactChanges(); 
   }
}

StackBlitz Demo