使用Angular 7从Firebase Storage检索图像

6

我无法在我的Angular 7应用中显示存储在Firebase存储中的图像。如何在不使用服务的情况下,从存储的根目录中简单检索图像,然后在HTML中循环以显示图像。

我已经尝试了不同的方法来获取下载URL,但它们都没有起作用。其他方法需要使用服务,而我不想在这种情况下使用服务。

组件

import { Component, OnInit } from '@angular/core';
import { AngularFireStorage, AngularFireStorageReference } from '@angular/fire/storage';
import { Observable } from 'rxjs'

@Component({
  selector: 'app-imageviewer',
  templateUrl: './imageviewer.component.html',
  styleUrls: ['./imageviewer.component.css']
})

export class ImageviewerComponent implements OnInit {
  images: Observable<any[]>;

  constructor(private storage: AngularFireStorage) {
    storage.ref("/").getDownloadURL().subscribe(downloadURL => {
      this.images = downloadURL;

    });
   }
}

HTML

        <div class="gal-list-view">
          <div style="margin: 20px">
              <div class="responsive" style="margin: 20px">
                  <div class="gallery" *ngFor="let image of images | async">
                    <a target="_blank">
                      <img src="{{image.url}}" alt="" width="600" height="400">
                    </a>
                    <div class="desc">Img Title</div>
                  </div>
              </div>         
          </div>
        </div>

我希望只能看到图片,但页面上没有显示任何内容。如果我在第一页并点击前往显示图库的链接,它只会显示空白页并且链接仍然是第一页。但是当我删除 'storage.ref(“/”)。getDownloadURL()。subscribe(downloadURL => { this.images = downloadURL;' 时,第一页可以前往图片库。

1个回答

6
使用服务来实现任何复杂逻辑是推荐的做法。它使 Angular 应用程序更加模块化,并提供可重用的方法。
您可以使用以下代码将图像上传到 Firebase 存储,并同时获取每个上传的 downloadUrl。
export class UploadService {
  private basePath = '/images';
  file: File;
  url = '';

  constructor(private afStorage: AngularFireStorage) { }

  handleFiles(event) {
    this.file = event.target.files[0];
  }

  //method to upload file at firebase storage
  async uploadFile() {
    if (this.file) {
      const filePath = `${this.basePath}/${this.file.name}`;    //path at which image will be stored in the firebase storage
      const snap = await this.afStorage.upload(filePath, this.file);    //upload task
      this.getUrl(snap);
    } else {alert('Please select an image'); }
  }

  //method to retrieve download url
  private async getUrl(snap: firebase.storage.UploadTaskSnapshot) {
    const url = await snap.ref.getDownloadURL();
    this.url = url;  //store the URL
    console.log(this.url);
  }
}

现在,这个 url 引用 可以在任何地方用于显示图片。
出于以上提到的原因,我建议使用服务来实现此操作。如果有任何不清楚的地方,请随意发表评论。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接