Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular Firestore - serverTimestamp #1205

Closed
stubborncoder opened this issue Oct 4, 2017 · 17 comments
Closed

Angular Firestore - serverTimestamp #1205

stubborncoder opened this issue Oct 4, 2017 · 17 comments

Comments

@stubborncoder
Copy link

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?.

@sionfletcher
Copy link

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

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

@eduardowickertg
Copy link

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 :/

@Toxicable
Copy link

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

@Wanted92
Copy link

Wanted92 commented Oct 6, 2017

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

@Toxicable
Copy link

@Wanted92 @eduardowickertg I explained what's going on here #1215 (comment)

@callen5914
Copy link

@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
Copy link

@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);
  }

}

@rubs
Copy link

rubs commented Oct 11, 2017

@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.

@soft-circles
Copy link

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(),

@stubborncoder
Copy link
Author

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()

@jlguenego
Copy link

jlguenego commented Dec 31, 2018

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();

@mhlg
Copy link

mhlg commented Feb 13, 2019

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

@Sroose
Copy link

Sroose commented Dec 12, 2019

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

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

@SpiegelSoft
Copy link

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

@JoseGazpar
Copy link

any update in 2022? pls

@BarnT
Copy link

BarnT commented Dec 22, 2022

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.

@fotgs
Copy link

fotgs commented Jan 16, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests