Search code examples
angularangularfire2

Error while reading user from Firebase Ionic Angular


I get an error while trying to read and store user email.

addroom.page.ts: constructor:

constructor(private crudService: CrudService, private fbauth: AngularFireAuth) { }

Method:

async createRecord() {
    const user = await this.fbauth.authState.pipe(first()).toPromise();
    const record = {};
    record['Name'] = this.roomName;
    record['Number'] = this.roomNumber;
    record['Description'] = this.roomDescription;
    record['User'] = user;
    this.crudService.create_NewRoom(record).then(resp => {
      this.roomName = "";
      this.roomNumber = undefined;
      this.roomDescription = "";
      this.roomUser = user.email;
      console.log(resp);
    })
      .catch(error => {
        console.log(error);
      });
  }

service.ts(CrudService):

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

@Injectable({
  providedIn: 'root'
})
export class CrudService {

  constructor(
    private firestore: AngularFirestore
  ) { }

  create_NewRoom(record) {
    return this.firestore.collection('Rooms').add(record);
  }

  read_Rooms() {
    return this.firestore.collection('Rooms').snapshotChanges();
  }

  update_Room(recordID,record){
    this.firestore.doc('Rooms/' + recordID).update(record);
  }

  delete_Room(recordID) {
    this.firestore.doc('Rooms/' + recordID).delete();
  }
}

Imports:

import { Component, OnInit } from '@angular/core';
import { CrudService } from '../service/service';
import { AngularFireAuth } from '@angular/fire/auth';
import { first } from "rxjs/operators";

And I get an error:

ERROR Error: Uncaught (in promise): FirebaseError: [code=invalid-argument]: Function DocumentReference.set() called with invalid data. Unsupported field value: a custom Q object (found in field User)

Any help would be appreciated!


Solution

  • Like the error suggest, you cannot store custom objects, in this case a Firebase.User. You need to extract the properties you want, for example:

    record['User'] = { email: user.email, displayName: user.displayName };
    

    I though like to work with a table, where I store all data related to a user, for easier access and no need to extract specific data. So in this case I would just store uid of the user when creating "new room" and have the user data in a separate table. That is just my suggestion :)