【问题标题】:I cant't recive data from firestore with Angular我无法使用 Angular 从 Firestore 接收数据
【发布时间】:2020-10-24 10:52:31
【问题描述】:

我使用了来自 @angular/fire/database 的 AngularFireList 从 firestore 获取数据,而 firestore 包含数据但我无法从中获取任何数据。

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from '@angular/fire/database';
import { Customer } from '../shared/customer.model'; 

@Injectable({
  providedIn: 'root'
})
export class CustomerService {

customersRef: AngularFireList<any>;    // Reference to Student data list, its an Observable
customerRef: AngularFireObject<any>;   // Reference to Student object, its an Observable too


// Inject AngularFireDatabase Dependency in Constructor
constructor(private db: AngularFireDatabase) { }

getCustomersList() {
   this.customersRef = this.db.list('customers');
   return this.customersRef;
}


 getCustomer(id: string) {
   this.customerRef = this.db.object('customers/' + id);
   return this.customerRef;
}}

【问题讨论】:

    标签: angular typescript google-cloud-firestore


    【解决方案1】:

    如果你想在可观察对象或方法上使用 Angular 的 http 调用,你需要在你的代码中使用 .subscribe() 方法:

    getCustomersList() {
       this.db.list('customers').subscribe(customers => {
          this.customersRef=costumers;
          console.log(consumers) //too se the data recived
        });
       return this.customersRef;
    }
    

    【讨论】:

      【解决方案2】:

      在服务中不需要以声明的方式存储值。 你可以返回

      getCustomersList(): Observable<AngularFireList<any>> {
         return this.db.list('customers');
      }
      
      
       getCustomer(id: string): Observable<AngularFireObject<any>> {
         return this.db.object('customers/' + id);
      }
      

      在组件或其他抽象中当你想使用这个流时你可以使用

      const customer$ = this.service.getCustomer();
      customer$.subscribe((customer)=>console.log(customer))
      

      或在html模板中

      <div>{{customer$ | async}}
      

      但您需要创建字段customer$: Observable&lt;AngularFireObject&lt;any&gt;&gt; = service.getCustomer();

      【讨论】:

      • 感谢您的回复。我更新了代码,它返回给我这个问题:类型 'AngularFireList' is missing the following properties from type 'Observable>': _isScalar, source, operator, lift, and 6 mor
      • 请在 Stackblitz 上展示您的全部代码。您遇到的错误意味着您可能在没有订阅的情况下将 Observable 用作 AngularFireList。很难猜出在哪里:(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      相关资源
      最近更新 更多