【发布时间】:2020-07-01 02:55:57
【问题描述】:
我正在编写一个显示一些产品的网站,每个产品都有一张图片。 为此,我必须做两件事:1.)从后端加载产品。 2.) 从后端加载图片。
现在图像不会显示,因为在从后端加载图像时,HTML 视图已经被渲染/构建。那时图像还没有。当我有更多产品时,越往下的产品的图像就会正确显示。
我了解到首选的解决方案是使用路由解析器在渲染组件之前预加载图像,因此我实现了产品解析器服务:
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;
}))
}
在我的组件中,我运行以下代码来获取刚刚预加载的图像:
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.
}
在我的 app-routing.module.ts 中,我将它添加到路由中:
path: '', component: ProductsComponent, resolve: { map: ProductResolverService }
图像 blob 的加载有点工作,blob 就在那里,但它们以对象的形式出现,而不是地图。在OnInit() 中可以看到console.log 命令的三个日志:
现在我的问题是如何从该对象访问 blob? 如果我可以访问 blob,我可以将它们放在我的函数 createImageFromBlob(blob) 中然后显示它们,这在以前有效。但我只是没有从对象中取出斑点。
而且,这已经非常复杂了,而且有点乱。这想必是很多人都会遇到的问题,难道没有更好的加载图片的解决方案吗?
编辑:我使用 Java Spring Boot 作为后端,并将图像本地存储在每个产品的单独文件夹中。我与产品一起保存在我的 SQL 数据库中的每个图像的文件名。所以在将图片加载到产品时,我首先需要从数据库中加载图片文件名,然后才能从本地存储中加载图片。
【问题讨论】:
标签: javascript angular angular-resolver