Skip to content

Firestore - Allow for class instance to be added to list #1335

@Supamiu

Description

@Supamiu

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions