Basically, the questions is how to change the format of observable returned to the interface format. What I mean is, when I get a data from a database it has a format as: id, name, img_path, description. But I want to assign the result to interface:
export interface IGallery {
id: number;
thumb: string;
img: string;
description? : string;
}
when I use my service:
images:IGallery[];
this._dataService.getEventGallery()
.subscribe(
images => {
//images
this.images = images; <-- how to convert to interface here
console.log(this.images);
},
err => {
console.log(err);
}
);
In order to display those images using *ngFor.
Currently I solved like this, but this is not a best solution:
.subscribe(
images => {
let result = images;
let finalArray = [];
for (var i = 0; i < result.length; i++) {
console.log(result[i]);
finalArray.push({thumb: "assets/img/1/events/" + result[i].img_path, img: "assets/img/1/events/" + result[i].img_path, description: result[i].description});
}
this.images = finalArray;
console.log(this.images);
},
err => {
console.log(err);
}
);
That's why we have the map operator.
This should do the trick (assuming getEventGallery()
returns an array, which your code seems to indicate it does):
images:IGallery[];
this._dataService
.getEventGallery()
.map((images) => {
return images.map((image) => {
return {
thumb: "assets/img/1/events/" + image.img_path,
img: "assets/img/1/events/" + image.img_path,
description: image.description
};
});
})
.subscribe(
images => {
//images
this.images = images;
console.log(this.images);
},
err => {
console.log(err);
}
);