首页 > 解决方案 > angularfire2 上传后显示图片

问题描述

使用Example Usage中的示例代码。我能够成功上传图像文件并显示它的链接。但是,我想在上传后立即在 img 标签中显示图像,而不是链接。我将如何做到这一点?我尝试过这样的事情无济于事:

  profileUrl: Observable<string | null>;

  ....


  const task = this.storage.upload(path, file);
  const ref = this.storage.ref(path);
  this.uploadPercent = task.percentageChanges();
  console.log('Image uploaded!');

  task.snapshotChanges().pipe(
    finalize(() => this.downloadURL = this.profileUrl = ref.getDownloadURL())
  )
  .subscribe();

在我的模板文件中:

<img [src]="profileUrl | async" />

所有这些都来自示例,但我需要将示例用法下载文件部分结合起来。

标签: javascriptfirebase-storageangularfire2

解决方案


我想到了。您不能订阅快照,但可以订阅下载参考。

  const task = this.storage.upload(path, file);
  const ref = this.storage.ref(path);
  this.uploadPercent = task.percentageChanges();
  console.log('Image uploaded!');
  task.snapshotChanges().pipe(
    finalize(() => {
      this.downloadURL = ref.getDownloadURL()
      this.downloadURL.subscribe(url => (this.image = url));
    })
  )
  .subscribe();

推荐阅读