angularfire icon indicating copy to clipboard operation
angularfire copied to clipboard

Angular Firestore - serverTimestamp

Open stubborncoder opened this issue 9 years ago • 17 comments

Hello, trying to figure out how to get a server timestamp with angularfire2/firestore,

I tried this but it does not work:

import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Ticket } from '../../model/interfaces/ticket.interface';

import * as fs from 'firebase/firestore';

@Injectable()
export class FirestoreProvider {

  private ticketsCollection:AngularFirestoreCollection<Ticket>;

  constructor( private afStore:AngularFirestore )
  {
    this.ticketsCollection = afStore.collection<Ticket>('Tickets');
  }
  
  addTicket(ticket:Ticket){
    ticket.createdAt = fs.FieldValue.serverTimestamp();  //<-- This will be null and throw an error.
    return this.ticketsCollection.add(ticket);
  }
}

Is there any other way to set the server timestamp in a document field?.

stubborncoder avatar Oct 04 '17 16:10 stubborncoder

Seems to work if you import all of firebase...

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

sionfletcher avatar Oct 04 '17 17:10 sionfletcher

maaan.. I'm getting mad at this.

`private clientsCollection: AngularFirestoreCollection;

constructor(private db: AngularFirestore) {
}

getAll() {
    return this.db.collection<ClientModel>('clients');
}

add(client: ClientModel) {
    this.clientsCollection = this.db.collection<ClientModel>('clients');
    return this.clientsCollection.add(client);
}`

Look at this, it is a simple add ObjectModel to collection, but when I try to execute it I receive this:

Function CollectionReference.add() requires its first argument to be of type object, but it was: a custom ClientModel object

It is almost the same as your piece of code, but it does not work :/

eduardowickertg avatar Oct 04 '17 21:10 eduardowickertg

@eduardowickertg I don't think you issue is related to this issue.

Toxicable avatar Oct 05 '17 04:10 Toxicable

@eduardowickertg I have the same problem and I'm getting mad, @Toxicable Do you have a simple solution?

emmeci92 avatar Oct 06 '17 08:10 emmeci92

@Wanted92 @eduardowickertg I explained what's going on here https://github.com/angular/angularfire2/issues/1215#issuecomment-334577913

Toxicable avatar Oct 06 '17 09:10 Toxicable

@stubborncoder does your add method work? Without the the time stamp? I followed the docs and didn’t use the second line where you use “return xxxx”. Maybe that’s why my add method is broken.

callen5914 avatar Oct 10 '17 22:10 callen5914

@stubborncoder I think I found something that you could try for timestamps. It works for me wonderfully!

import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import * as firebase from 'firebase';
import { Observable } from 'rxjs/Observable';

export interface Announcement { id: string; title: string; body: string, createdAt: Date }

@Component({
  selector: 'app-announcement-form',
  templateUrl: './announcement-form.component.html',
  styleUrls: ['./announcement-form.component.css']
})
export class AnnouncementFormComponent implements OnInit {

  private announcementCollection: AngularFirestoreCollection<Announcement>;
  announcements: Observable<Announcement[]>;

  constructor(private afs: AngularFirestore) { 
  	this.announcementCollection = afs.collection<Announcement>('announcements');
    this.announcements = this.announcementCollection.valueChanges();
  }

  ngOnInit() {
  	console.log("Hello");
  }

  addAnnouncement(title: string, body: string){
  	const id = this.afs.createId();
    const createdAt = new Date();
    console.log(createdAt);
  	const announcement: Announcement = {id: id, title: title, body:body, createdAt: createdAt };
  	console.log(announcement);
  	this.announcementCollection.add(announcement);
  }

}

callen5914 avatar Oct 11 '17 00:10 callen5914

@callen5914 yes my method works without the timestamp line, your suggestion works fine but bear in mind that you are saving the client's date value, and I would like that field to be more reliable to avoid messing with ordering that collection for example.

With new Date() you will set the date to whatever date you user has in her computer...

Sorry I loged as another user, I'm still the original poster.

rubs avatar Oct 11 '17 06:10 rubs

I'm also having this issue as @stubborncoder. I'm working in Ionic 3 and I've imported angularfire2 and the Firestore module but when I call

import { AngularFirestore } from 'angularfire2/firestore';
import { Injectable } from '@angular/core';

@Injectable()
export class FirebaseService {

    constructor(private db: AngularFirestore) { }
    addUser(user) {
        this.db.collection("users").doc(user.id).set({
            firstName: user.firstName,
            lastName: user.lastName,
            email: user.email,
            DoB: user.dateOfBirth,
            created_at: this.db.firestore.FieldValue.serverTimestamp(),
            updated_at: this.db.firestore.FieldValue.serverTimestamp()
        }).then(res => {
            console.log("User created. ")
        }).catch(error => {
            console.error("Error adding user: ", error);
        });
    }

I get property "FieldValue" does not exist on type Firestore when I call:

this.db.firestore.FieldValue.serverTimestamp(),

soft-circles avatar Oct 25 '17 23:10 soft-circles

As @sionfletcher stated some days ago, you have to use the whole firebase thingy, the service approach here does not work for some reason:

import * as firebase from ‘firebase’; ticket.createdAt = firebase.firestore.FieldValue.serverTimestamp()

stubborncoder avatar Oct 26 '17 06:10 stubborncoder

Just a small improvement for going to production with Firestore. If you don't want to see warning development messages.

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

ticket.createdAt = firebase.firestore.FieldValue.serverTimestamp();

jlguenego avatar Dec 31 '18 18:12 jlguenego

import * as firebase from 'firebase/app'; still get the warning It looks like you're using the development build of the Firebase JS SDK.

mhlg avatar Feb 13 '19 01:02 mhlg

even cleaner: import { firestore } from 'firebase/app';

ticket.createdAt = firestore.FieldValue.serverTimestamp();

Sroose avatar Dec 12 '19 16:12 Sroose

This is useful, but it's not at all easy to test.

SpiegelSoft avatar Feb 18 '20 16:02 SpiegelSoft

any update in 2022? pls

JoseGazpar avatar Nov 28 '22 19:11 JoseGazpar

This works for me (with version: "@angular/fire": "7.5.0"):

import { serverTimestamp } from "@angular/fire/firestore";
//...
ticket.createdAt = serverTimestamp()

With this, you don't need to explicitly install the firebase package.

BarnT avatar Dec 22 '22 13:12 BarnT

@BarnT Thanks, man! Finally, this worked for me (even though I'm using angular/fire 7.4)

fotgs avatar Jan 16 '23 18:01 fotgs