user3760959
user3760959

Reputation: 455

Firebase is not uplodaing data to the database

I'm working on an Angular+Firebase project. I'm trying to upload my data to the firebase database. But I'm getting an error while doing do. Below is my FirebaseService Code.

import { AngularFirestore } from 'angularfire2/firestore';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database';
import { AngularFireObject, AngularFireList } from 'angularfire2/database';
import * as firebase from 'firebase';

@Injectable()
export class FirebaseService {
  listings ;
  listing: Observable<any[]>;
  folder: any;

  constructor(private db: AngularFireDatabase) {
    this.folder = 'listingimages';
   }

  getListings(){

      this.listings = this.db.list('/listings').snapshotChanges().map(actions => {
        return actions.map(action => ({ key: action.key, ...action.payload.val() }));
      })
      return this.listings;
  }

  getListingDetails(id){
    this.listing = this.db.object('/listings/'+id).valueChanges() as Observable<Listing[]>;
    return this.listing;

  }

  addListing(listing){
    //Create Root Reference     
        let storageRef = firebase.storage().ref();
    for(let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
      let path = `/${this.folder}/${selectedFile.name}`;
      let iRef = storageRef.child(path);
      iRef.put(selectedFile).then((snapshot) => {
        listing.image = selectedFile.name;
        listing.path = path;
        console.log(this.listings);
        return this.listings.push(listing);

        });
    }
  }

}

interface Listing{
    $key?: string;
    title?: string;
    type?: string;
    image?: string;
    city?: string;
    owner?: string;
    bedrooms?: string
}

The screenshot of the error which appears in console is as below :enter image description here

I'm not getting why it is showing undefined error?

Upvotes: 0

Views: 53

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

this.listings is only being assigned in your getListings and getListingDetails methods. But you're accessing it in addListing. What's probably happening is that you're calling addListing before you ever call one of the other methods.

If you want to call those methods in any order, you're going to have to find another way to write to the database that doesn't depend on something else happening earlier.

Upvotes: 1

Related Questions