Angular 2 Firebase 存储 - 上传完成时的图像预览

Angular 2 Firebase Storage - Image preview on upload finish

我试图在 uploadTask 成功后显示上传的 img,但由于异步加载,视图试图在上传完成之前显示它。

这是方法:

upload(value){
    let file = value.target.files[0];
    let storageRef = firebase.storage().ref('noticias/' + file.name);
    let uploadTask = storageRef.put(file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      function(snapshot) {
        let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log('Upload is ' + progress + '% done');
        switch (snapshot.state) {
          case firebase.storage.TaskState.PAUSED: // or 'paused'
            console.log('Upload is paused');
            break;
          case firebase.storage.TaskState.RUNNING: // or 'running'
            console.log('Upload is running');
            break;
        }
      }, function(error) {
      switch (error) { 
        case 'storage/unauthorized':
          break;

        case 'storage/canceled':
          break;

        case 'storage/unknown':
          break;
      }
    }, function() {
      // Upload completed successfully, now we can get the download URL
      let downloadURL = uploadTask.snapshot.downloadURL;
      console.log('Upload done!');
    });

    storageRef.getDownloadURL().then(url => this.imgUrl = url);
    this.uploadedImg = true;
  }

这是视图:

<img *ngIf="uploadedImg" [src]="imgUrl" />

该方法的最后两行加载过早。我还尝试将它们移动到成功函数中。问题是,如果我将它们移到那里,this 不再指代 class 并且我无法更改视图中的值。

丢失对 this 的引用是 javascript 中的一个常见问题,有一个简单的模式可以跟踪它。你在 success 函数中移动行是正确的,只是在开始时这样做:

upload(value){
    let that = this;
    let file = value.target.files[0];

现在 that 将始终指向原始 this,并且以下将按预期工作:

}, function() {
    // Upload completed successfully, now we can get the download URL
    let downloadURL = uploadTask.snapshot.downloadURL;
    console.log('Upload done!');
    // Using original `this`
    storageRef.getDownloadURL().then(url => that.imgUrl = url);
    that.uploadedImg = true;
});