1

While entering data to firebase database I am facing this error Uncaught (in promise ) : [object Object]. I am able to upload image to storage. But when other data like email and password are not being enter. Here I have created my own table to store user data

enter image description here Please help

register.html

<!--
  Generated template for the RegistrationPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Registration</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
    <form [formGroup]="form"  (ngSubmit)="saveUser(form.value)">

      <ion-item>
        <ion-label floating>Email Address</ion-label>
        <ion-input type="text" formControlName="email" [(ngModel)]="userEmail"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label floating>Password</ion-label>
        <ion-input type="password"  formControlName="password" [(ngModel)]="userPassword"></ion-input>
      </ion-item>
        <ion-item>
          <span ion-text color="danger" block text-center padding-top padding-bottom (click)="selectImage()">Select an image</span>
          <input type="hidden" name="image" formControlName="image" [(ngModel)]="userImage">
          <img [src]="userImage">
        </ion-item>

      <button ion-button clear >Register</button>
    </form>

</ion-content>

register.ts

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular';

import { UserProvider } from './../../../providers/database/user/user';
import { PreloaderProvider } from './../../../providers/preloader/preloader';
import { ImageProvider } from './../../../providers/image/image';

import { User } from '../../../models/user';
import * as firebase from 'firebase';

/**
 * Generated class for the RegistrationPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-registration',
  templateUrl: 'registration.html',
})
export class RegistrationPage {
  public form: any;
  public userImage: any;
  public users: any;
  public userEmail : any = ' ';
  public userPassword : any = '';
  public userPic : any = ' ';
  public userId : string = ' ';



  constructor(
    private _FB: FormBuilder,
    private _IMG: ImageProvider,
    public viewCtrl: ViewController,
    private _LOADER: PreloaderProvider,
    private _DB: UserProvider,
    public navCtrl: NavController, public navParams: NavParams) {

      this.form  = _FB.group({
        'email' : [' ', Validators.required],
        'password' : [' ', Validators.required],
        'image' : [' ', Validators.required]
      });
      this.users = firebase.database().ref('users/');
  }

  saveUser(val) {
    this._LOADER.displayPreloader();

    let email: string = this.form.controls["email"].value,
      password: string = this.form.controls["password"].value,
       image : string = this.userImage;

       console.log(email + password + image);
       this._DB.uploadImage(image)
       .then((snapshot : any) => {

         let uploadImage : any = snapshot.downloadURL;

         this._DB.addToDatabase({
            email : email,
            password : password,
            image : uploadImage
         })
         .then((data)=> {
          this._LOADER.hidePreloader();
         });
       });
  }

  selectImage() {
    this._IMG.selectImage()
      .then((data) => {
        this.userImage = data;
      });
  }


}

provider/database/user.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';


import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase';

/*
  Generated class for the UserProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class UserProvider {

  constructor(public http: Http) {
    console.log('Hello UserProvider Provider');
  }



  addToDatabase(userObj): Promise<any> {
    return new Promise((resolve) => {
      let addRef = firebase.database().ref('users');
      addRef.push(userObj);
      resolve(true);
    });
  }

  updateDatabase(id, userObj) : Promise<any>
  {
    return new Promise((resolve) => {
      var updateRef = firebase.database().ref('users').child(id);
      updateRef.update(userObj);
      resolve(true);
    });
  }

  deleteDatabase(id) : Promise<any>
  {
    return new Promise((resolve) => {
      let ref = firebase.database().ref('users').child(id);
      ref.remove();
      resolve(true);
    });
  }

  uploadImage(imageString) : Promise<any>
  {
    let image : string = 'user-' + new Date().getTime() + '.jpg',
         storageRef : any,
         parseUpload : any;

         return new Promise((resolve, reject) => {
           storageRef = firebase.storage().ref('users/' + image);
           parseUpload = storageRef.putString(imageString, 'data_url');

           parseUpload.on('stage_change', (_snapshot) => {

           },
           (_err) => {
             reject(_err);
           },
          (success) => {
            resolve(parseUpload.snapshot);
          });
       });
  }


}

2 Answers 2

2

Hi, Maybe this will help you what I did in my case to upload an image in firebase storage.

.html File

<ion-row>
    <ion-col>
        <input type="file" (change)="capturePicGallery($event)" />
    </ion-col>
</ion-row>

.ts file

    capturePicGallery(event){
    this.imagPathSrc =  event.srcElement.files[0];
   firebase.storage().ref().child(pathStoreImage).put(this.imagPathSrc).then((snapshot) => {
    console.log("snapshot.downloadURL" ,snapshot.downloadURL);
            });
    }
Sign up to request clarification or add additional context in comments.

2 Comments

can you please let me know how can I implement your code in mine. I am quite new to ionic
also are you storing the image url in firebase database?
0
 accessGallery(sourceType:number) {
/**
 this.accessGallery(0);//photo library
 this.accessGallery(1);//camera
 **/
const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  sourceType:sourceType,
}
this.camera.getPicture(options).then((imageData) => {
  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  this.base64Image = 'data:image/jpeg;base64,' + imageData;
  this.images.push(this.base64Image);
  this.upload(this.base64Image);
}, (err) => {
 // Handle error
});
}

upload(event) {
// way 1 (not working)
// let data = new File(event,'demo.jpg');
// console.log("data",data);
// this.afStorage.upload('/products/', data);

// way 2
this.afStorage.ref(`products/${Date.now()}.jpeg`).putString(event, 'data_url')
.then(url => console.log("upload success",url))
}

then you can access camera or get image from library and upload it

<button (click)="accessGallery(0)">select image then upload</button>
<button (click)="accessGallery(1)">capture image then upload</button>

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.