angular - 如何使上传的图片立即可见
问题描述
我正在创建一个允许用户将图片上传到 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>
解决方案
根据您共享的代码片段(不包括 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';
});
}
推荐阅读
- python - 使用 Cv2 放大图像?
- javascript - GMail - 通过 JQuery/Javascript 将邮件标记为重要
- c - read() 没有按预期工作。成功读取大块时返回值 1
- python - 我的表单无法接收 request.files。我遇到无法上传用户个人资料照片的问题。img 通过 request 方法正确发送
- c - ncurses 带有信号的 getch() 行为
- swiper - Swiper.js 变量 + 动态宽度幻灯片,基于图像宽度
- android - 如何用用户可以在 Android Studio Kotlin 中更改的字符串替换 documentPath?
- c++ - 如何解决分段错误单链表?
- r - 将命名向量传递到 str_replace_all 以替换多个模式
- typescript - 无法窥探原始值;给定的未定义