【问题标题】:Retrieve Images from Firebase Storage Using Angular 7使用 Angular 7 从 Firebase 存储中检索图像
【发布时间】:2019-09-27 21:15:39
【问题描述】:

我无法在我的 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>

我只想查看图片显示,但页面上没有显示任何内容。如果我在第 1 页并单击链接转到显示图片库的页面,它只显示一个空白页面,并且链接仍然是第 1 页。但是当我取出 'storage.ref("/").getDownloadURL ().subscribe(downloadURL => { this.images = downloadURL;` 第 1 页转到图片库。

【问题讨论】:

    标签: firebase firebase-storage angular7


    【解决方案1】:

    建议使用服务来实现任何复杂的逻辑。它使 Angular 应用程序更加模块化,并且还提供了可重用的方法。

    您可以使用以下代码将图片上传到Firebase Storage,并同时获取每次上传的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 参考 可以在任何地方使用来显示图像。

    出于上述原因,我建议使用服务来实现这一点。 如果有任何不清楚的地方,请随时发表评论。

    【讨论】:

      猜你喜欢
      • 2020-10-23
      • 2017-01-16
      • 1970-01-01
      • 2017-08-30
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      相关资源
      最近更新 更多