簡體   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