0

我正在编写一个显示一些产品的网站,每个产品都有一个图像。为此,我必须做两件事:1.)从后端加载产品。2.)从后端加载图像。

当前状态

现在图像没有显示,因为在从后端加载图像时,HTML 视图已经被渲染/构建。那时图像还没有。当我有更多产品时,越往下的产品的图像就会正确显示。

我读到首选的解决方案是使用路由解析器在渲染组件之前预加载图像,所以我实现了 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; 

  }))
}

在我的组件中,我运行以下代码来获取刚刚预加载的图像:

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 }

图像斑点的加载有点工作,斑点就在那里,但它们作为对象出现,而不是地图。console.log您可以从以下命令中看到三个日志OnInit()

我的控制台日志

现在我的问题是如何从该对象访问 blob?如果我可以访问这些 blob,我可以将它们放在我的函数 createImageFromBlob(blob) 中,然后显示它们,这在以前有效。但我只是没有从物体中取出斑点。

而且,这已经非常复杂了,而且有点混乱。这一定是很多人都面临的问题,难道没有更好的加载图片的解决方案吗?

编辑:我使用 Java Spring Boot 作为后端,并将图像本地存储在每个产品的单独文件夹中。我与产品一起保存在我的 SQL 数据库中的每个图像的文件名。因此,在将图像加载到产品时,我首先需要从数据库中加载图像文件名,然后才能从本地存储中加载图像。

我在后端的图像文件夹

4

1 回答 1

0

我建议不要使用 Blob,为什么不只提供“https://your-site.com/imgs/vw-polo.jpg”之类的图像路径?您能否提供有关您的任务和后端的更多信息?

于 2020-06-30T18:39:31.740 回答