I am loading data from an image from html using * ngFor.
To load the image, another function is performed, which needs the ID that is loaded in * ngFor, to find the image with that ID.
To get the image, I used (click) where I pass the product ID, but the goal is to load the images without using the click, ie automatically.
What I have
HTML
<div class="row tab-pane Galeria">
<div *ngFor="let product of products" class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
<div class="image-item" (click)="fillModal($event, product)">
<a class="d-block image-block h-100">
<homeImage>
<img *ngIf [src]="Images" class="Images img-fluid" alt="">
</homeImage>
</a>
<div class="ImageText" (click)="ImageInfo(product.id)">{{product.name}}</div>
</div>
</div>
</div>
Component.ts
ngOnInit() {
this.GetProducts();
}
GetProducts() {
let self = this;
this.Global.refreshToken().subscribe(function (result) {
self.homeService.getProducts().then(function (resultado) {
if (resultado) {
self.products = resultado;
}
}).catch();
});
}
ImageInfo(id) {
var self = this;
self.Global.refreshToken().subscribe(function (result) {
self.homeService.getImage(id).then(function (resultado) {
if (resultado) {
self.Images = resultado;
}
}).catch();
});
}
Service.ts
getProducts(): Promise<any> {
let self = this;
let urlAux = self.url + "/Products/GetProducts";
return axios.get(urlAux, {
headers: {
Authorization: 'Bearer ' + localStorage.getItem("access_token")
}
})
.then(this.extraData)
.catch(this.handleErroPromisse);
}
getImage(id): Promise<any> {
let self = this;
let urlAux = self.url + "/Products/GetImage/" + id;
return axios.get(urlAux, {'responseType': 'arraybuffer'})
.then((response) => {
let image = btoa(
new Uint8Array(response.data)
.reduce((data, byte) => data + String.fromCharCode(byte), '')
);
return `data:${response.headers['content-type'].toLowerCase()};base64,${image}`;
});
}
What I tested and didn't work:
Does not work execute the function in a src :(
<div class="row tab-pane Galeria">
<div *ngFor="let product of products" class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
<div class="image-item" (click)="fillModal($event, product)">
<a class="d-block image-block h-100">
<homeImage>
<img *ngIf [src]="ImageInfo(product.id)" class="Images img-fluid" alt="">
</homeImage>
</a>
<div class="ImageText">{{product.name}}</div>
</div>
</div>
</div>