首页 > 解决方案 > 如何使上传的图片立即可见

问题描述

我正在创建一个允许用户将图片上传到 Firebase 存储的 Ionic 应用程序。我遇到的问题是,只有在我关闭应用程序并重新打开后选择了新图片时,它才会更改图片。我希望它在上传后立即更改。当它被删除时,立即恢复到占位符图片。

它正在工作,但您只能在关闭应用程序并重新打开页面后才能看到图片。

打字稿:

    constructor(private router: Router,
              private authService: AuthService,
              private imageService: ImageService,
              private afAuth: AngularFireAuth) {

      this.afAuth.authState.subscribe(user => {
      this.userId = user.uid
      console.log('constructoruser', this.userId);
      });
              }

  ngOnInit() {
          this.firestore.ref(`/Photos/${ this.userId }/`).child('photo0').getDownloadURL().then((url) => {
          this.photo0 = url;
        }).catch((error) => {
          console.log(error.message);
          this.photo0 = 'assets/img/add-an-image.png';
          console.log(this.photo0);
        });
  }

HTML:

<div>
    <img [src]="photo0" (click)="UploadPic0('photo0')"/>
</div>   

标签: angulartypescriptfirebaseionic4

解决方案


根据您共享的代码片段(不包括 UploadPic0 方法),这是因为您在组件初始化期间仅从 url 设置图像一次(ngOnInit,仅调用一次)。

现在可能的解决方案:
- 创建一个将更新图像的新方法(到图像 url 或备用图像)
- 在 ngOnInit 中调用此方法,并在收到有关图像上传的成功/失败消息时调用此方法。
- 作为故障保护(确保在图像更新后调用渲染方法),调用更改检测器。

就像是

updateImage() {
        this.firestore.ref(`/Photos/${this.userId}/`).child('photo0').getDownloadURL().then((url) => {
         this.photo0 = url;
        }).catch((error) => {
          console.log(error.message);
          this.photo0 = 'assets/img/add-an-image.png';
        });
}

推荐阅读