繁体   English   中英

Angular 4刷新 <img src={{ … }} > 当价值变化时

[英]Angular 4 refresh <img src={{ … }} > when the value changes

我正在使用Angular 4,我有一个组件,我想更改我的用户当前的照片..所以显示当前用户照片的HTML代码是这个..

<div class="profilphoto">
        <img src= {{currentphoto}}>
</div>

currentphoto包含当前用户的照片网址,我从firebase获取它。之后,我显示了一个照片库,以便用户可以选择一个并使用表单更改他的个人资料照片..提交代码如下,工作正常

    onSubmit = function(form) {
    this.photoUrl = form.photoUrl;
    firebase.database().ref("users/"+this.authService.cusername+"/photo").update({
      url: form.photoUrl
    }).then(()=>{
      this.currentphoto = this.authService.photourl;
      console.log("currentphoto:"+this.currentphoto);
    }
    );
  }

一切正常,只是不顾currentphoto值已发生变化,数据库URL upadated的HTML仍显示前一个用户的图像和恼人的(如果我刷新页面,它显示了新PROFIL图片)..有什么办法可以使

<div class="profilphoto">
        <img src= {{currentphoto}}>
</div>

检测currentphoto何时更改值并使用新的src值显示图像?

尝试手动调用changedetection

constructor(private cdRef: ChangeDetectorRef){

}

设置图像后

 this.currentphoto = this.authService.photourl;
 this.cdRef.detectChanges();

没有你的组件/服务的整个代码很难知道是什么问题,但最好的镜头是在这一行:

onSubmit = function(form) {

可能这是'this'值的问题。 在此行下方(在函数内)插入一个console.log(this),并检查'​​this'是否是对组件实例或窗口的引用。

尝试使用箭头功能:

onSubmit = form => {
 //do what you need here, call the service, etc...
 //and then set the this.currentphoto
}

这可能不再相关,但如果它可以帮助人们更快地解决这个问题,这就是它。

如果你想在更改后更新图像,请写下你的src,如下所示:
SRC = '{{currentphoto}} D = {{clock_tick}}'

首次加载组件时(我使用Date.now())并在更新图像后再次初始化时钟标记。 这将告诉您的浏览器您更新了图像,它将为您重新加载它。

它对我有用。

你试过这个:

<div class="profilphoto">
        <img [src]="currentphoto" >
</div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM