Search code examples
angularangularfire2

How to get serverTimestamp via Angularfire or firebase


I can't find a way to get serverTimestamp from firestore. Either with firestore itself, or with angularfire.

I found a lot of github issues with solutions, which doesn't work. I guess that's because of a different version?

"@firebase/app": "^0.1.10",
"angularfire2": "^5.0.0-rc.6.0",
"firebase": "^4.13.1",

Code alternatives I've tried:

import * as firebase from 'firebase';
firebase.firestore.FieldValue.serverTimestamp();

ERROR TypeError: Cannot read property 'FieldValue' of undefined

import * as firebase from 'firebase';
firebase.database.ServerValue.TIMESTAMP;

ERROR TypeError: Cannot read property 'ServerValue' of undefined

constructor( private afs: AngularFirestore ) { }
this.afs.firestore.FieldValue.serverTimestamp();

Property 'FieldValue' does not exist on type 'FirebaseFirestore'.


Solution

  • What helped at the end was uninstalling everything firebase related, so as I mentioned in my question:

    "@firebase/app": "^0.1.10",
    "angularfire2": "^5.0.0-rc.6.0",
    "firebase": "^4.13.1",
    

    And running npm install firebase angularfire2 --save again.

    This gave me:

    "angularfire2": "^5.0.0-rc.7",
    "firebase": "^5.0.1",
    

    Which fixed all my problems.

    Import firebase as:

    import * as firebase from 'firebase';
    

    The timestamp code itself:

    get timestamp() {
      return firebase.firestore.FieldValue.serverTimestamp();
    }
    

    EDIT on 17th november: If you'll use the previously mentioned import import * as firebase from 'firebase';, you'll get this warning in developer console:

    It looks like you're using the development build of the Firebase JS SDK. When deploying Firebase apps to production, it is advisable to only import the individual SDK components you intend to use.

    For the module builds, these are available in the following manner (replace with the name of a component - i.e. auth, database, etc):

    CommonJS Modules: const firebase = require('firebase/app'); require('firebase/');

    ES Modules: import firebase from 'firebase/app'; import 'firebase/';

    Typescript: import * as firebase from 'firebase/app'; import 'firebase/';

    So change it to:

    import * as firebase from 'firebase/app';
    import 'firebase/firestore';