开发者问题收集

如何在兼容模式下在 angular/Fire 中使用 serverTimestamp

2024-03-27
78

我尝试过

import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
const firestore = firebase.firestore;

this.form = this.builder.group({
      items:[data.items, null],
      dateReported:[firestore.FieldValue.serverTimestamp(), Validators.required],
    ....})

我收到此错误:

错误 FirebaseError:函数 WriteBatch.update() 调用时使用了无效数据。不支持的字段值:自定义 sl 对象(在字段 dateReported 中找到)

{
    "items": [
        {
            "sku": "2756",
            "qty": 1,
            "name": "\tImpresora Artillery X3 Plus"
        }
    ],
    "dateReported": {
        "_methodName": "serverTimestamp"
    },
    "dateModified": {
        "_methodName": "serverTimestamp"
    },
    "trialsAndResults": "cable suelto",
    "inspectedItems": [
        {
            "sku": "2756",
            "qty": 1,
            "name": "\tImpresora Artillery X3 Plus",
            "dictum": "repair"
        }
    ],
    "status": "examined",
    "technician": "Cristobal",
    "charge": 0,
    "report": null
}

也尝试过

import { serverTimestamp } from 'firebase/firestore';
import { AngularFirestore } from '@angular/fire/compat/firestore';

constructor(private afs: AngularFirestore, ...) {
    this.form = this.builder.group({
        dateReported: [serverTimestamp(), Validators.required],
        ...
    });

    const batch = this.afs.firestore.batch();
    const orderRef = this.afs.firestore.collection(...).doc(....);
    batch.update(orderRef, this.form.value);
    batch.commit()
}

同样的错误

尝试过

import firebase  from 'firebase/compat/app';
dateReported:[firebase.firestore.FieldValue.serverTimestamp(), Validators.required],

错误 TypeError:无法读取未定义的属性(读取“FieldValue”)

"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/fire": "^17.0.1",
"@angular/forms": "^17.3.0",
"@angular/material": "^17.2.2",
"firebase": "^9.23.0",
2个回答

尝试一下

从 '@angular/fire/compat/firestore' 导入 { AngularFirestore }; 从 '@angular/forms' 导入 { FormBuilder, Validators };

构造函数(private afs:AngularFirestore,private builder:FormBuilder){

this.form = this.builder.group({
    dateReported: [null, Validators.required], // Initialize with null value
});

>

romina_sh
2024-04-08

此错误通常发生在您尝试访问的属性不存在或尚未初始化时。因此,我建议做的第一件事是使用可选链。

[firebase?.firestore?.FieldValue?.serverTimestamp(), Validators.required]
desoga
2024-04-07