未捕获(承诺):[对象]离子3&角火基地

时间:2018-03-17 08:05:53

标签: angular ionic3

在向firebase数据库输入数据时,我面临此错误未捕获(在承诺中):[object Object]。我可以将图像上传到存储。但是当没有输入电子邮件和密码等其他数据时。在这里,我创建了自己的表来存储用户数据

enter image description here 请帮忙

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;
      });
  }


}

提供商/数据库/ 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 个答案:

答案 0 :(得分:2)

<强>嗨, 也许这会帮助你在我的案例中做的就是在firebase存储中上传图像。

.html文件

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

.ts文件

    capturePicGallery(event){
    this.imagPathSrc =  event.srcElement.files[0];
   firebase.storage().ref().child(pathStoreImage).put(this.imagPathSrc).then((snapshot) => {
    console.log("snapshot.downloadURL" ,snapshot.downloadURL);
            });
    }

答案 1 :(得分: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))
}

然后您可以访问相机或从库中获取图像并上传

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

enter image description here