简体   繁体   中英

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

I am using Angular 4 and I have a component where I want to change my user current photo.. so the html code that displays the current user photo is this..

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

currentphoto contains the current user photo url and I get it from firebase.. After that I display a Gallery of photos so the user can select one and change his profil photo using a form.. the submit code is the following and works fine

    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);
    }
    );
  }

Everything works fine except that despite the currentphoto value has changed and database url upadated the html still displays the previous user's image and its annoying(if I refresh the page it shows the new profil image).. Is there any way I can make

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

detect when currentphoto changes value and Display the image with the new src value??

Try calling the changedetection manually,

constructor(private cdRef: ChangeDetectorRef){

}

Once you set the image

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

Without the entire code of your component/service is hard to know what is the problem, but the best shot is in this line:

onSubmit = function(form) {

probably it's a problem with the 'this' value. Insert a console.log(this) below this line (inside the function) and check if 'this' is a reference to the component instance or to the window.

Try to use arrow function:

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

This is probably not relevant anymore but in case it could help people get this solved faster, here it is.

If you want to update the image after it has changed write your src like this:
src='{{currentphoto}}?d={{clock_tick}}'

Initialize your clock tick when you first load your component (I use Date.now()) and again after you update the image. This will tell your browser that you updated the image and it will reload it for you.

It worked for me.

Have you tried this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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