【问题标题】:Angular Firestore How do I retrieve a sub collection document for editing?Angular Firestore 如何检索子集合文档进行编辑?
【发布时间】:2018-08-22 12:30:10
【问题描述】:

我正在尝试从 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('GotDocs: ', this.animalInfo) 返回未定义。

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() 中使用上述代码是否是解决此问题的正确方法。

非常感谢任何帮助。

迈克尔

【问题讨论】:

    标签: angular google-cloud-firestore


    【解决方案1】:

    就像@JeffD23 说的:

    您想在 ngIf 中执行“(animalInfo | async) as animal”(推荐解决方案)

    那么您的 html 中不再需要异步管道,请记住在括号 {{}} 中使用新名称。如果您忘记了给对象起的名称,请使用 {{ animal | json }} 这会将对象显示为 json 文本。

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

    或者你可以在 constructor()/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 中再次执行此操作 {{ 动物信息 | json }}

    【讨论】:

    • 谢谢罗伯特。我错过了 ngIf 中的 animalInfo。我认为阅读太多看不够;)
    【解决方案2】:

    阅读单个文档有一种更简单的方法。您已经有了 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)
    

    【讨论】:

    • 感谢 Jeff,我回顾了你的书,只用了几行代码就实现了我所追求的目标。
    【解决方案3】:

    animalInfo 是可观察类型。

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

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

    我希望这会有所帮助:)

    【讨论】:

    • 感谢 Jihoon Kwon,帮了大忙。我可以在 console.log() 中看到正确的数据,但在 html 中看不到。我已经尝试过 this.animalInfo = collection$.subscribe,然后是 html 中的 {{ animalInfo.name }} 和其他变体。没有出现任何错误,只是没有在页面上显示数据。
    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多