简体   繁体   English

Firestore:检索单个文档

[英]Firestore : Retrieve a single document

I want to retrieve a single document from Firestore. 我想从Firestore检索单个文档。 So I do not mean the list of documents in the collection (I know how to do that). 所以我不是指集合中的文档列表(我知道该怎么做)。 Let's say I know one of the key-value pair of the document and I would like to find and retrieve the document into Angular 4. 假设我知道文档的一个键值对,我想找到并将文档检索到Angular 4中。

 interface Occupations { duration: number; id_entity: number; id_job: number; id_user: number; salary: number; start_time: number; } occupationDoc:AngularFirestoreDocument<Occupations>; occupation: Observable<Occupations>; 
 <h1>A specific post:</h1> <h3>{{ (occupation | async)?.salary }}</h3> <p>{{ (occupation | async)?.id_user }}</p> <p>{{ (occupation | async)?.duration }}</p> <p>{{ (user | async)?.lastName }}</p> 

Use flatmap to return the single document data: 使用flatmap返回单个文档数据:

First import the .flatMap() property. 首先导入.flatMap()属性。

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

Then query your collection and limit it to 1 document: 然后查询您的集合并将其限制为1个文档:

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. 然后你可以订阅它,它将返回flatened json而不是数组。

EDIT: 编辑:

And you can just do like this to use it in your html directly: 你可以这样做直接在你的html中使用它:

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

In the html code: 在html代码中:

<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');
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM