角4刷新当值改变

问题描述:

我使用角4,我有一个组件,我想改变我的用户当前的照片..所以,显示当前用户的照片是这个HTML代码..角4刷新<img src={{ ... }} >当值改变

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

currentphoto包含当前用户照片网址,我得到它的火力.. 之后,我展示的照片库,使用户可以选择一个和使用形式改变了他的照片PROFIL ..提交代码是以下并且工作正常

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值的图像?

+2

难道不该'[来源] = “currentphoto”'? – jonrsharpe

+1

'currentphoto'是否有新值?如果值相同(换句话说,图片改变但网址保持不变),您将不得不添加一个随机数作为查询字符串的url。如https://stackoverflow.com/questions/17394440/add-random-variable-after-image-url-with-javascript –

+0

是的抱歉,如果我还没有明确这一点.. currentphoto值包含标准图像网址,所以当用户更改profil image当前照片值变化 – Zekelonas

尝试调用手动changedetection

constructor(private cdRef: ChangeDetectorRef){ 

} 

一旦你设置图像

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

我有和OP相同的问题,并且可以确认此解决方案可以解决此问题。我的问题是,在任何时候Angular会有修复,还是这是所需的行为? – Ben

+0

其实,我还必须添加一个随机数,如上面Christian的评论所述,并在https://stackoverflow.com/questions/17394440/add-random-variable-after-image-url-with-javascript中解释。这带来了随机数冲突的问题,这导致问题是否有更好的解决方案? – Ben

你有没有尝试过这样的:

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

我现在试过但仍然不工作.. – Zekelonas

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

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 
}