首页 文章

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

提问于
浏览
2

我试图从firestore子集合中检索单个文档:database / users / uid / animal / 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('GotDocs:',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 回答

  • 3

    阅读单个文档有一种更简单的方法 . 您已经拥有该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)
    
  • 0

    animalInfo是可观察的类型 .

    Angular2支持'| async'管道直接显示可观察类型 . 所以,如果你想获得真正的数据值,你应该像这样使用subscribe:

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

    我希望这会有所帮助:)

  • 0

    喜欢@JeffD23说:

    你想在ngIf(推荐的解决方案)中做“(animalInfo | async)动物”

    那么你的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}}

相关问题