girish
girish

Reputation: 301

Image getting cached in Angular

I am using angular version 9. I have 2 components. 1 to search a car make, model and 2nd component to load the details of the car that is selected from component 1. I pass the image link for the car from the car that is selected from component 1 to component 2 and load that image in component 2. This works fine..

When I browse to some other page in my application and again go to the component 1 and select a different car and go to component 2, the image of the previously selected car shows for around 1-2 seconds and then my new image is shown. This looks like a browser caching problem. I have tried to load a loader image initially till my new image completes loading and then show the newly loaded image but it does not work. What I have tried is as below.

<img *ngIf="isLoading" [src]="loadingimage.png" />
<img [hidden]="isLoading" [src]="carModelImage" (load)="isLoading = false"/>

What I have noticed is, the moment component 2 is opened the (load) event on the img tag fires and changes the isLoading value to false even without waiting for the new carModelImage to load and thus the previous image shows for some time.

My component code looks like below.

@Component({
selector: 'app-request-summary',
templateUrl: './request-summary.component.html',
styleUrls: ['./request-summary.component.scss']
})

export class RequestSummaryComponent implements OnInit, OnDestroy {
    public carModelImage: string = '';
    public isLoading: boolean = true;

   constructor() {
     this.carModelImage = '';
     this.isLoading = true;
   }


   ngOnInit() {
   this.requestSummaryService.carData
    .pipe(takeUntil(this.ngUnsubscribe))
    .subscribe((data) => {
      this.carModelImage = data[0].carModelImage ? data[0].carModelImage 
      :'http://nocarimage.png';
    }
   }

   ngOnDestroy() {
     this.isLoading = true;
     this.carModelImage = '';
     this.ngUnsubscribe.next();
     this.ngUnsubscribe.complete();
   }
}

I am struglling due to this issue since quite a long. Any help will be highly appreciated.

Upvotes: 1

Views: 1121

Answers (2)

Muthukumaran
Muthukumaran

Reputation: 187

How do you assign carmodelImage variable . The carmodelImage is responsible for showing the previous image, if you could nullify it on destroy may be it should help

Assuming you said ngondestroy is being called

Upvotes: 1

Damian C
Damian C

Reputation: 2171

Well, I don't have much to go on here, but I'll share a simple pattern with you.

When your image is no longer being displayed null it out.

For example somewhere in your code you probably write this:

carModelImage = "your-image";

When you are sure you no longer need this var anymore, null it out.

carModelImage = null;

Post more code if you want help specific to your issue.

Upvotes: 1

Related Questions