firebase / firebase/firebase-js-sdk
FR: Allow for class instance to be passed as data
- Dominant language
- TypeScript
- Stars
- 5.1k
- Forks
- 1k
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 37
Description
### [REQUIRED] Describe your environment
* Operating System version: Windows 10
* Firebase SDK version: 4.6.0
* Firebase Product: Firestore
### Describe the problem
When trying to add a document to a collection or to set it, the item has to be of type `object`, meaning that it can't be an instance of any class.
The error is:
> FirebaseError: Function CollectionReference.add() requires its first argument to be of type object, but it was: a custom Item object
#### Steps to reproduce:
Simply run this in an angular 5.0.0 environment with angularfire2 5.0.0-rc.3:
```
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: `
-
{{ item.name }}
`
})
export class AppComponent {
private itemsCollection: AngularFirestoreCollection;
items: Observable;
constructor(private afs: AngularFirestore) {
this.itemsCollection = afs.collection('items');
this.items = this.itemsCollection.valueChanges();
}
addItem(item: Item) {
this.itemsCollection.add(item);
}
}
```
I 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())`, which is kinda ugly but works like a charm.
Contributor guide
Assessment
This issue has not been assessed yet.