Angular Firestore如何检索子集合文档以进行编辑?

时间:2018-03-14 04:42:41

标签: angular google-cloud-firestore

我正在尝试从firestore子集合中检索单个文档: 数据库/用户/ UID /动物/ docID的

我能够成功解析从另一个组件解析的docID,但我正在努力检索要在html中显示的信息:

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { AngularFireAuth} from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Router, ActivatedRoute } from '@angular/router';

interface Animal {
 name: string;
 age: number;
 sex: string;
 breed: string;
 colour: string;
 }

 interface animID extends Animal {
   id: string;
 }

  @Component({
  selector: 'app-detail-animal',
  templateUrl: './detail-animal.component.html',
  styleUrls: ['./detail-animal.component.css']
})
export class DetailAnimalComponent implements OnInit {

 curUser: any; // This used to maintain the logged in user. 
 animalDoc: AngularFirestoreDocument<Animal>;
 animalCol: AngularFirestoreCollection<Animal>;
 animalInfo: any;
 petID: Observable<Animal>;

 constructor(
  public auth: AuthService, 
  private afs: AngularFirestore, 
  private afAuth: AngularFireAuth, 
  private router: Router,
  public route: ActivatedRoute
  ) {
  const petID: string = route.snapshot.paramMap.get('id'); 
  console.log('AnimId from route: ', petID)
  const user: any = this.afAuth.authState
 }
 private curPetID: string = this.route.snapshot.paramMap.get('id');

 ngOnInit() {
  this.afAuth.auth.onAuthStateChanged((user) => {

  if (user) {
    // get the current user    
    this.curUser = user.uid;
    console.log('Animal ID:', this.curPetID )
    console.log('Current User: ', this.curUser);
    // Specify the Collection
    this.animalInfo = this.afs.collection(`users/${this.curUser}/animals/`, 
    ref => ref.where('id', "==", this.curPetID)
        .limit(1))
        .valueChanges()
        .flatMap(result => result)
        console.log('Got Docs:', this.animalInfo);
      }
    });
  }
}

然后在我的HTML中(现在只显示它):

<strong>Name: {{ (animalInfo | async)?.name }}</strong>
<br>Breed: {{ (animalInfo | async)?.breed }}
<br>Animal System ID: {{ (animalInfo | async)?.id }}

当我运行代码时,在console.log(&#39; GotDocs:&#39;,this.animalInfo)中返回undefined。

Got Docs: 
 Observable {_isScalar: false, source: Observable, operator: MergeMapOperator}
 operator:MergeMapOperator {project: ƒ, resultSelector: undefined, concurrent: 
 Infinity}
 source:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar:false
__proto__:
Object

我不确定在ngOnInit()中使用上述代码是否也是正确的方法。

非常感谢任何帮助。

迈克尔

3 个答案:

答案 0 :(得分:4)

阅读单个文档有一种更简单的方法。您已拥有ID,因此您可以指向ngOnInit中的特定文档:

const docRef = this.afs.doc(`users/${this.curUser}/animals/${this.curPetID}`)
this.animalInfo = docRef.valueChanges()

理想情况下,您在HTML中打开此数据并设置模板变量。

<div *ngIf="animalInfo | async as animal">

  Hello {{ animal.name }}

</div>

或者您可以在组件TypeScript中订阅它。

animalInfo.subscribe(console.log)

答案 1 :(得分:0)

animalInfo是可观察的类型。

Angular2 +支持&#39; |异步&#39;管道直接显示可观察的类型。 因此,如果您想获得真实的数据值,您应该使用如下订阅:

const collection$: Observable<Item> = collection.valueChanges()
collection$.subscribe(data => console.log(data) )

我希望这会有所帮助:)

答案 2 :(得分:0)

像@ JeffD23一样说:

你想做&#34;(animalInfo | async)动物&#34;在ngIf(推荐的解决方案)

然后你的html中不再需要异步管道,请记得在括号{{}}中使用新名称。如果你忘记了你给对象的名字,只需使用{{animal | json}}这将把对象显示为json文本。

const ref = 'location in db';
const animalInfo$: Observable<Item>;
constructor(private service: Firestore) {
  this.animalInfo$ = this.service.doc(ref).valueChanges();
}

或者你可以在构造函数()/ onInit()(备份解决方案)中执行异步部分

const ref = 'location in db';
const animalInfo: Item;
constructor(private service: Firestore) {
  this.service.doc(ref).subscribe(item => {
    this.animalInfo = item;
    console.log(item);
  );
}

然后你可以在你的HTML中再次这样做     {{animalInfo | json}}