lif*_*bag 6 firebase firebase-storage angular7
我无法在我的 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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我只想看到图像显示,但它没有在页面上显示任何内容。如果我在第 1 页并单击链接转到显示图片库的页面,它只显示一个空页面,并且链接仍然是第 1 页。但是当我取出 'storage.ref("/").getDownloadURL ().subscribe(downloadURL => { this.images = downloadURL;` 第 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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这个url 引用可以在任何地方使用来显示图像。
出于上述原因,我建议使用服务来实现这一点。如果有什么不清楚的,请随时发表评论。
| 归档时间: |
|
| 查看次数: |
5509 次 |
| 最近记录: |