当值更改时,Angular 4刷新<img src="{{" ...="" }}=""/>

时间:2017-10-10 16:32:42

标签: javascript jquery html angular typescript

我正在使用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 值已更改且数据库网址已更新,html仍会显示上一个用户的图像并且令人讨厌(如果我刷新页面,显示新的profil图像)..有什么方法可以制作

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

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

4 个答案:

答案 0 :(得分:6)

尝试手动调用 changedetection

constructor(private cdRef: ChangeDetectorRef){

}

设置图像后

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

答案 1 :(得分:1)

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

onSubmit = function(form) {

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

尝试使用箭头功能:

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

答案 2 :(得分:1)

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

如果要在更改后更新映像,请像下面这样编写src:
src ='{{currentphoto}}?d = {{clock_tick}}'

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

对我有用。

答案 3 :(得分:0)

你试过这个:

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