Angularfire: Firestore - Allow for class instance to be added to list

Created on 9 Nov 2017  路  2Comments  路  Source: angular/angularfire

When trying to add a document to a collection, the item has to be of type object, meaning that it can't be an instance of any class.

Version info

Angular: 5.0.0

Firebase: 4.5.0

AngularFire: 5.0.0-rc.3

How to reproduce these conditions

Steps to set up and reproduce

Simply run this:

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

export class Item { name: string; getName():string{return this.name;} }

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of items | async">
        {{ item.name }}
      </li>
    </ul>
  `
})
export class AppComponent {
  private itemsCollection: AngularFirestoreCollection<Item>;
  items: Observable<Item[]>;
  constructor(private afs: AngularFirestore) {
    this.itemsCollection = afs.collection<Item>('items');
    this.items = this.itemsCollection.valueChanges();
  }
  addItem(item: Item) {
    this.itemsCollection.add(item);
  }
}

Sample data and security rules

Basic free-for-all security rules are enough to run the test.

Debug output

* Errors in the JavaScript console *

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

EDIT: Same for doc<T>().update.

Expected behavior

We should be able to add a custom class object to a collection, because T (in collection<T>) can be a class type, not only an interface.

Actual behavior

We can't add such an item in a collection, had to write this to make a temporary fix (on my top-level firestore data model class):

getData(): object {
        const result = {};
        Object.keys(this).map(key => result[key] = this[key]);
        return result;
    }

Then I replaced add(item) by add(item.getData()).

Most helpful comment

Just in case someone comes here and want to see how it's going: https://github.com/firebase/firebase-js-sdk/issues/311

All 2 comments

Hey @Supamiu! This is not a limitation of AngularFire but of the Firestore SDK. You can file an issue here: https://github.com/firebase/firebase-js-sdk/issues.

Just in case someone comes here and want to see how it's going: https://github.com/firebase/firebase-js-sdk/issues/311

Was this page helpful?
0 / 5 - 0 ratings

Related issues

StephenFluin picture StephenFluin  路  3Comments

sharomet picture sharomet  路  3Comments

avanderbergh picture avanderbergh  路  3Comments

jteplitz picture jteplitz  路  3Comments

harrylincoln picture harrylincoln  路  3Comments