【问题标题】:Angularfire dependency injection - TS2339 property firestore does not exist on type CartserviceAngularfire 依赖注入 - TS2339 属性 firestore 在 Cartservice 类型上不存在
【发布时间】:2021-01-19 14:33:48
【问题描述】:

我正在将 angularefire 添加到 angular.io 的“看一看教程”(购物车)中。尝试使用 firebase firestore 替换 products.ts 和 shipping.json,并编写一个 forders 文件替换“您的订单已提交”。得到它的工作有点但是....

在 cart.service.ts 中

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
//angularfire
import { AngularFirestore} from '@angular/fire/firestore';
import { Observable } from 'rxjs';

@Injectable()
export class CartService {

  items = [];
//angularfire
  fshipping: Observable<any[]>;
  afs: AngularFirestore;

  constructor(
    private http: HttpClient,
//angularfire
    firestore: AngularFirestore
  ) { 
    this.fshipping = firestore.collection('fshipping').valueChanges();
    this.afs = firestore;
  }

  addToCart(product) {
    this.items.push(product);
  }
  getItems() {
    return this.items;
  }

  clearCart() {
    this.items = [];
    return this.items;
  }

  getShippingPrices() {
//angularfire
    // return this.http.get('/assets/shipping.json');
    return this.fshipping;
  }

//angularfire
  placeOrder(customerData) {
    const orderColl = this.afs.collection<any>('forders');
//    const orderColl = this.firestore.collection<any>('forders');
    orderColl.add({
      name: customerData.name, 
      address: customerData.address
    });
  }

}

fshipping(在构造函数内部)工作并替换了 shipping.json。 但是在 placeOrder 方法中我必须使用 this.afs.collection('forders')... 如果我使用 this.firestorre.collection .... 出现以下错误

src/app/cart.service.ts:45:28 中的错误 - 错误 TS2339:“CartService”类型上不存在属性“firestore”。

第 45 行:

const orderColl = this.firestore.collection<any>('forders');

在研究其他在线教程时,他们可以在其他方法中使用通过构造函数注入的 firestore。我错过了什么?谢谢。

【问题讨论】:

    标签: angular typescript firebase google-cloud-firestore angularfire


    【解决方案1】:

    错误是告诉您您的对象中没有名为firestore 的属性。也许您打算使用afs 属性:

    const orderColl = this.afs.collection<any>('forders');
    

    【讨论】:

      【解决方案2】:

      我认为你在构造函数中做错了,而不是:

      this.fshipping = firestore.collection('fshipping').valueChanges();
      this.afs = firestore;
      

      删除this.afs = firestore;并仅保留:

      this.fshipping = this.firestore.collection('fshipping').valueChanges();
      

      并在 placeOrder 方法中,而不是:

      const orderColl = this.afs.collection<any>('forders');
      

      做:

      const orderColl = this.firestore.collection<any>('forders');
      

      同样在你的构造函数中,不要忘记将firestore 标记为私有:

      constructor(private http: HttpClient, private firestore: AngularFirestore)
      

      【讨论】:

        猜你喜欢
        • 2016-03-14
        • 2017-02-25
        • 2021-11-24
        • 2019-01-11
        • 2021-05-08
        • 2021-10-15
        • 2019-01-21
        • 2020-12-13
        • 2021-08-04
        相关资源
        最近更新 更多