2017-10-10 47 views
2

我使用角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

回答

2

嘗試調用手動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

1

你有沒有嘗試過這樣的:

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

我現在試過但仍然不工作.. – Zekelonas

1

沒有你的組件的整個代碼/服務很難知道什麼是問題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 
}