angular - 将数据添加到 Firebase Cloud Firestore 和 Angular

标签 angular firebase object google-cloud-firestore

首先我必须说我正在学习 Angular。也许答案太明显了,但我看不到。我在网上搜索了类似问题的回复,但没有找到适合我的答案。

我制作了一个 Angular 模板驱动表单来将产品存储在我的 Firebase Cloud Firestore 数据库中。我创建了一个名为“Product”的模型

product.ts

export class Product {
constructor(
    public code: string,
    public desc: string,
    public stock: number,
    public price: number,
    public off: number,
    public details?: string
) {}

然后,我有 product.component.ts

import { Component } from '@angular/core';
import { Product } from './product';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';


@Component({
    selector: 'app-admin-product',
    templateUrl: 'product.component.html'
})

export class AdminProductComponent {

model = new Product('', '', 0, 0, 0);
successMsg = 'Data successfully saved.';

productsRef: AngularFirestoreCollection<Product>;
product: Observable<Product[]>;

constructor(private afs: AngularFirestore) {
    this.productsRef = this.afs.collection<Product>('productos');
}

save() {
    this.productsRef.add(this.model).then( _ => alert(this.successMsg));
}

TypeScript 根本不返回错误,一切似乎都正常。但是当我运行我的应用程序并尝试保存表单数据时,控制台返回下一个错误:

AdminProductComponent.html:51 ERROR Error: Function CollectionReference.add() requires its first argument to be of type object, but it was: a custom Product object

我解决了将自定义对象传递给这样一个简单对象的问题:

const product = {
    code: this.model.code,
    desc: this.model.desc,
    stock: this.model.stock,
    price: this.model.price,
    off: this.model.off,
    details: this.model.details
}

像这样保存数据:

save() {
    this.productsRef.add(product).then( _ => alert(this.successMsg)); }

但我认为这不是正确的解决方案,可能会导致 future 在调用应用程序时出现问题。

最佳答案

我使用了 typescript 扩展运算符

  add(wizard: Wizard): Promise<DocumentReference> {
    return this.wizardCollection.add({...wizard});
  }

关于angular - 将数据添加到 Firebase Cloud Firestore 和 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47110905/

相关文章:

javascript - 如何使用 Angular 8 在选择元素中取消选择选定的选项元素

angular - 如何将 AWS CodeStar 用于 Angular 应用程序?

firebase - flutter 网络 : White screen (PersistedOffset error)

java - 对象1.toString() == 对象2.toString()

javascript - jQuery Javascript 将父对象传递为 this

对象的 JavaScript 方法不起作用

javascript - 当我使用服务通信时触发变化检测

javascript - 在 addEventHandler 中测试代码

xcode - 如何使用 Firebase Swift 3 创建 CompletionHandler

Angular 11 在 SSR @nguniversal/express-engine ReferenceError : globalThis is not defined 上运行