【问题标题】:Angular: HTML page finishes rendering before images are loaded from backendAngular:HTML页面在从后端加载图像之前完成渲染
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 这可能是个好主意,但我将图像存储在本地,无法通过 URL 访问它们。也许我应该在开始时将它们上传到我页面的隐藏子 URL,然后每次我需要它们时从那里获取它们?但这听起来也不是一个好的解决方案。附言。我现在在问题的末尾添加了关于我的后端信息的编辑。
    • 您只需创建一个名为“images”的文件夹并存储名为“product_1”、“product_2”等的文件。
    • 抱歉,我认为这行不通。在前端我无法使用图像创建文件夹,我需要将它们下载到用户的电脑/手机上,不是吗?
    猜你喜欢
    • 2020-09-18
    • 2011-08-15
    • 1970-01-01
    • 2014-03-06
    • 2018-07-26
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多