5

我想从 Firestore 中检索单个文档。所以我不是指集合中的文档列表(我知道该怎么做)。假设我知道文档的一个键值对,我想在 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> 

4

2 回答 2

3

使用 flatmap 返回单个文档数据:

首先导入 .flatMap() 属性。

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

然后查询您的集合并将其限制为 1 个文档:

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

然后您可以订阅它,它将返回扁平化的 json 而不是数组。

编辑:

你可以这样做直接在你的html中使用它:

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

在html代码中:

<p>{{ (userInfo | async)?.duration }}</p>
于 2017-11-09T15:10:17.270 回答
0

这是我想出的解决方案:

//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');
    });
于 2017-11-09T20:48:44.147 回答