I'm programming a website that displayes some products and each product has an image. For this I have to do 2 things: 1.) load the products from backend. 2.) load the images from backend.
Right now the images don't get shown, because while loading the images from the backend, the HTML View already gets rendered / build up. At that time the images are not there, yet. When I had more products, the further down products had their images properly displayed.
I read that the preferred solution is to use a route resolver to pre load the images before rendering the component, so I implemented a Product Resolver Service :
export class ProductResolverService implements Resolve<any> {
map = new Map();
constructor(private _data: DataService, private router: Router) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this._data.getProducts().pipe(map(myProducts => { //getProducts() loads all product from the database and returns an Observable<Product[]>
myProducts.forEach(myProduct => {
//takes the myProduct and loads the image as a BLOB from backend. Then puts that blob into this.map.
this.loadMainProductPicture(myProduct);
})
return this.map;
}),
catchError(e => {
console.error(e);
this.router.navigate(['users']); // the rerouting worked when I put an error on purpose in the part above
return null;
}))
}
And in my component I run following code to get the just preloaded images:
ngOnInit() {
this.map = this.activatedRoute.snapshot.data['map'];
console.log(typeof(this.activatedRoute.snapshot.data['map'])) // object
console.log(this.map);
console.log(this.map.size); // 0
this.loadProducts(); //load all products from the database again (This works and has nothing to do with the images, I just didn't know how to return the products and the images from the Product Resolver Service, so I decided to only return the images and then load the products again here.
}
And in my app-routing.module.ts I added this to the routes:
path: '', component: ProductsComponent, resolve: { map: ProductResolverService }
The loading of the image blobs kinda works, the blobs are there, but they come as an Object, not a Map. You can see the three logs from the console.log
commands in OnInit()
:
Now my problem is how to access the blobs from that object? If I could access the blobs, I can put them in my function createImageFromBlob(blob) and then display them, this worked before. But I just don't get the blobs out of the object.
And also, this is super complicated already, and a bit messy with. This must be a problem many people face, isn't there a better solution to load the images?
EDIT: I'm using Java Spring Boot as backend and store the images locally in seperate folders for each product. The filename of each image I save with the product in my SQL Database. So when loading the image to a product, I first need to load the image filename from the database and then I can load the image from the local storage.