Problem with the UploadTask from putString()

2019-08-24 22:51发布

问题:

I am having problems with the UploadTask from Firebase Storage. I am trying to upload an image and then saving the image URL on Firestore Cloud. To do so I have this code:

newuploadImage() {
    this.image = 'movie-' + new Date().getTime() + '.jpg';
    let storageRef: any,
    parseUpload: any;
    storageRef = firebase.storage().ref('imgs/' + this.image);
    parseUpload = storageRef.putString(this.cameraImage, 'data_url')
    parseUpload.on('state_changed',
    function (snapshot) {
    }, function (error) {
    }, function () {
        // Upload completed successfully, now we can get the download URL
        parseUpload.snapshot.ref.getDownloadURL().then(function (downloadURL) {
            const idPubli = this.firestore.createId();
            const idReto = this.firestore.createId();
            let IDUser = firebase.auth().currentUser.uid;
            let img = downloadURL
            const idPuntPubli = this.firestore.createId();
            let participacionCreadora = true;
            let punt = 0;
            this.firestore.doc(`public/${idPubli}`).set({
                idPubli,
                idReto,
                IDUser,
                img,
                idPuntPubli,
                participacionCreadora,
                punt,
            })
        });
    })
}

The image is uploaded fine, however when It tries to execute the this.firestore, the console log is giving me this error:

ERROR TypeError: Cannot read property 'firestore' of undefined

I dont know how to get over that error.

EDIT

This is the import and the constructor in case there is something wrong.

import {  AngularFirestore} from 'angularfire2/firestore';

constructor(public camera: Camera, public firestore: AngularFirestore) {
  }

回答1:

You most likely hit a scope issue, which you can resolve by replacing this function:

.then(function (downloadURL)

With an arrow-function (which preserves the lexical scope).

.then((downloadURL) =>


回答2:

Sharing my code, may be it will be helpful for you.

  this.imageFile.name.substr(this.imageFile.name.lastIndexOf('.'));
  const fileRef = this.storage.ref(this.filePath);
  this.task = this.storage.upload(this.filePath, this.imageFile);
  this.uploadPercent = this.task.percentageChanges();
  this.task
    .snapshotChanges()
    .pipe(
      finalize(() => {
        this.downloadURL = fileRef.getDownloadURL();
        this.downloadURL.subscribe(url => {
          this.imageUrl = url;
        });
      })
    )
    .subscribe();
  return this.uploadPercent;
}