I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default
this is my solution for fallback on multi images. we basically detach the ChangeDetector once we resolve the image so we can reduce CPU on vm check cycles once image is resolved.
import {Component, ChangeDetectionStrategy, ChangeDetectorRef} from 'angular2/core';
import {AppStore} from "angular2-redux-util/dist/index";
@Component({
selector: 'logoCompany',
changeDetection: ChangeDetectionStrategy.Default,
template: `
{{getBusinessInfo('companyName')}}
`
})
export class LogoCompany {
constructor(private cdr:ChangeDetectorRef) {
}
private imageRetries:number = 0;
private unsub;
private detach() {
this.cdr.detach();
}
private getImageUrl() {
var url = '';
switch (this.imageRetries){
case 0: {
url = 'http://galaxy.example.me/Resources/Resellers/' + this.getBusinessInfo('businessId') + '/Logo.jpg'
break;
}
case 1: {
url = 'http://galaxy.example.me/Resources/Resellers/' + this.getBusinessInfo('businessId') + '/Logo.png'
break;
}
default: {
url = 'assets/person.png'
break;
}
}
return url;
}
private onImageLoaded() {
this.detach();
}
private onImageError() {
this.imageRetries++;
}
private getBusinessInfo(field):string {
return '12345';
}
}