简体   繁体   English

使用AngularFire2 / Firestore在Ionic / Angular中的模板中从文档字段中查找引用

[英]Looking up a reference from a document field from the template in Ionic/Angular with AngularFire2/Firestore

I am working on an Ionic 3 App (Uses Angular 4). 我正在使用Ionic 3 App(使用Angular 4)。 I am using Angularfire2 to interact with my Firestore database. 我正在使用Angularfire2与我的Firestore数据库进行交互。 Currently, I am retrieving a document as an observable and displaying it's fields in my template. 目前,我正在将文档作为可观察的文档进行检索,并在模板中显示其字段。

My problem is one of my fields in the document is a reference to another document (categories). 我的问题是我在文档中的一个字段是对另一个文档(类别)的引用。 from the template, I'm trying to do something like this: 从模板,我试图做这样的事情:

<ion-badge>{{ getCategory( (pro.element | async)?.category ) }}</ion-badge>

which is calling a function in my provider that looks like this: 这正在我的提供程序中调用如下函数:

getCategory(ref:AngularFirestoreDocument<Category>){
   if(ref){
     ref.valueChanges().subscribe(val =>{
       return val.name;
     });
   }
}

I have no idea if this is an appropriate/sustainable way to retrieve the reference document, as I have looked all over and not found any detailed documentation covering this. 我不知道这是否是检索参考文档的适当/可持续方式,因为我到处都看过,但没有找到涵盖此文档的详细文档。 When I log this it seems to iterate over thousands of times, returning a DocumentReference Object, but I get the error that valueChanges() isn't a function. 当我记录此消息时,它似乎迭代了数千次,返回了DocumentReference对象,但是我收到了valueChanges()不是函数的错误。

Any direction on best practice in this circumstance would be greatly appreciated. 在这种情况下,关于最佳实践的任何方向将不胜感激。

Thank you 谢谢

When you use async pipe thats mean you are dealing with observable or promise data. 当您使用异步管道时,这意味着您正在处理可观察的数据或Promise数据。 In getCategory function you have subscribed to observable and we know that async pipe will do that for us, so you should only format your data. 在getCategory函数中,您已订阅了observable,并且我们知道异步管道将为我们做到这一点,因此您应该仅格式化数据。

your function will be : 您的功能将是:

import {Observable} from 'rxjs/Observable';
import "rxjs/add/operator/of";

...

getCategory(ref:AngularFirestoreDocument<Category>){
   if(ref){
     ref.valueChanges().map(val =>{
       return val.name;
     });
   }
   else{
       //return an empty string to get rid of any error when there is no ref.
       return    Observable.of("");
   }
}

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

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