Firestore : Retrieve a single document

偶尔善良 提交于 2019-12-01 09:23:09

Use flatmap to return the single document data:

First import the .flatMap() property.

import { AngularFirestore } from 'angularfire2/firestore';
import 'rxjs/add/operator/mergeMap';

Then query your collection and limit it to 1 document:

this.afs.collection('collection', ref => ref.where('value', '==', true) 
.limit(1)).valueChanges().flatMap(result => result);

Then you can subscribe to that and it will return the flatened json instead of an array.

EDIT:

And you can just do like this to use it in your html directly:

this.userInfo = this.afs.collection('collection', ref => ref.where('value', 
'==', true).limit(1)).valueChanges().flatMap(result => result);

In the html code:

<p>{{ (userInfo | async)?.duration }}</p>

This is the solution I came up with :

//HTML
{{userInfo}}

//TypeScript
this.afs.collection('Occupations',
ref => ref.where('id_user', '==', this.idAuth)  
.limit(1))
.valueChanges()
.flatMap(result => result)
.subscribe(
    v => {
        let y = JSON.parse(JSON.stringify(v));
        this.userInfo = y.duration;                 
    }, 
    (error) => {
             console.log(error);
    }, () => {
        console.log('Finished');
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!