Angular Firestore - 获取文档数据并分配给变量

时间:2018-03-02 10:30:06

标签: angular typescript firebase google-cloud-firestore

我正在尝试将从firestore文档收集的数据分配给在构造函数之前初始化的Observable类型的变量。

我通过将动态invoiceId字符串传递给.doc()搜索来获取集合中的数据,我可以将数据分配给本地变量(如下所示),但是在尝试将其分配给此时.invoice,我收到以下错误:

  

未捕获(承诺):TypeError:无法设置未定义的属性'invoice'

-

组件:

@Html.DisplayFor(x => x.Cards[i].DisplayableNumber)

3 个答案:

答案 0 :(得分:1)

我正在打同样的事情。这让我抓狂!我是新手,但我似乎通过更改一行代码解决了您的问题:

.then(function(doc) {   //changed from
.then((doc) => {        //changed to (removed the function)

我甚至不理解这样做的后果,但范围现在正在分配变量的值。

答案 1 :(得分:1)

如果您使用的是AngularFire,您可以这样做:

invoiceCol: AngularFirestoreCollection<Invoice>;
invoiceObservableArray: Observable<Invoice[]>;
invoiceArray: Invoice[];

constructor(private db: AngularFirestore) { } //--injection

getAllInvoice() { //getting data of DB
    this.invoiceCol= this.db.collection('yourInvoiceDbPath');
    return this.invoiceCol.valueChanges();
}

this.invoiceObservableArray.getAllInvoice();//calling method above

this.invoiceObservableArray.subscribe(invoice=> { //converting oberv in array
      this.invoiceArray = invoice;
    });

console.log(this.invoiceArray); //showing in console

答案 2 :(得分:0)

getInvoice() {

let _this = this; <---***

    var docref = this.db.collection('/users').doc(this.authService.user.uid)
                     .collection('/invoices').doc(this.invoiceId);
    docref.ref.get()
        .then(function(doc) {
            if (doc.exists) {
                var invoice = doc.data(); <------WORKS
                // this.invoice = doc.data(); <------WORKS
                console.log('Invoice data: ', doc.data());
            } else {
                console.error('No matching invoice found');
            }
    })
  }