@Nativescript/firebase中firebase.firestore.Timestamp方法失效属性返回undefined
问题原因
- @nativescript/firebase v11.1.3默认开启了
timestampsAsDates配置,会自动将Firestore返回的Timestamp对象转换为JS原生Date对象,Date对象没有seconds属性,也没有toDate()方法,所以访问属性返回undefined,调用方法直接报错导致后续日志无输出。 - 代码存在语法错误:你调用了整个文档数据对象
hoge的toDate()方法,该方法只存在于Timestamp实例上,正确写法应为hoge.commented_at.toDate()。 - Vue 2不支持异步计算属性,你给computed属性加了async修饰符,返回值本质是Promise对象,所以模板渲染时会显示
object Promise。 - 该版本插件的
Timestamp静态类没有挂载在firebase.firestore对象下,直接调用firebase.firestore.Timestamp.now()会报错,无法输出日志。
解决方案
方案1:直接使用自动转换的Date对象(无需修改配置)
如果不需要操作Timestamp原生属性,直接把返回的commented_at当做标准JS Date对象使用即可,调用Date的原生方法处理时间:
// 示例 console.log(hoge.commented_at.getTime()) // 获取时间戳 console.log(hoge.commented_at.getFullYear()) // 获取年份
方案2:保留原始Timestamp对象
如果需要使用Timestamp的相关API,按以下步骤调整:
调整Firebase初始化配置(app.js)
import Vue from "nativescript-vue"; import Home from "./components/Home"; var firebase = require("@nativescript/firebase").firebase; firebase .init({ // 添加firestore配置,关闭自动转Date特性 firestore: { settings: { timestampsAsDates: false } } }) .then( function () { console.log("firebase.init done"); }, function (error) { console.log("firebase.init error: " + error); } ); new Vue({ render: (h) => h("frame", [h(Home)]), }).$start();
修正Home.vue代码
// 单独导入Timestamp类 import { firebase } from "@nativescript/firebase"; import { Timestamp } from "@nativescript/firebase/firestore"; export default { data() { return { message: '' } }, // 异步逻辑移到mounted钩子 async mounted() { const Ref = firebase.firestore .collection("comments") .doc("07bhQeWDf3u1j0B4vNwG"); const doc = await Ref.get(); const hoge = doc.data(); console.log("hoge.commented_at", hoge.commented_at); console.log("hoge.commented_at.seconds", hoge.commented_at.seconds); const hogeToDate = hoge.commented_at.toDate(); console.log("hogeToDate", hogeToDate); this.message = hogeToDate // 测试静态方法调用 const hogeTimestampNow = Timestamp.now(); console.log("当前Timestamp", hogeTimestampNow) } };
内容的提问来源于stack exchange,提问作者naokonakanish
相关产品推荐
相关产品推荐

