【问题标题】:Uncaught (in promise ) : [object Object] Ionic 3 & Angular firebase未捕获(承诺):[object Object] Ionic 3 & Angular firebase
【发布时间】:2019-02-18 02:07:21
【问题描述】:

在向 firebase 数据库输入数据时,我遇到了这个错误 Uncaught (in promise ) : [object Object]。我能够将图像上传到存储。但是当没有输入其他数据(如电子邮件和密码)时。这里我创建了自己的表来存储用户数据

请帮忙

注册.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>

注册.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);
          });
       });
  }


}

【问题讨论】:

    标签: angular ionic3


    【解决方案1】:

    嗨, 也许这会对我在 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);
                });
        }
    

    【讨论】:

    • 能否请您告诉我如何在我的代码中实现您的代码。我对离子很陌生
    • 你是否也将图像 url 存储在 firebase 数据库中?
    【解决方案2】:
     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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 2019-03-08
      • 1970-01-01
      • 2019-04-09
      • 2018-03-12
      • 1970-01-01
      • 2020-04-16
      • 2018-02-26
      相关资源
      最近更新 更多