0

我在使用 Firebase Storage 的 UploadTask 时遇到问题。我正在尝试上传图像,然后将图像 URL 保存在 Firestore Cloud 上。为此,我有以下代码:

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

图像上传正常,但是当它尝试执行this.firestore时,控制台日志给了我这个错误:

错误类型错误:无法读取未定义的属性“firestore”

我不知道如何克服这个错误。

编辑

这是导入和构造函数,以防出现问题。

import {  AngularFirestore} from 'angularfire2/firestore';

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

2 回答 2

1

您很可能遇到了范围问题,您可以通过替换此函数来解决该问题:

.then(function (downloadURL)

使用箭头函数(保留词法范围)。

.then((downloadURL) =>
于 2018-12-04T11:34:00.443 回答
0

分享我的代码,可能对你有帮助。

  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;
}
于 2018-12-04T13:12:55.927 回答