【问题标题】:Send too many request to server when need to get image with image [duplicate]当需要使用图像获取图像时向服务器发送太多请求[重复]
【发布时间】:2019-12-24 10:23:55
【问题描述】:

我想在 Angular 7 中使用 blob 从服务器获取图像。 我为发送请求编写了这个服务:

  downloadImage(id: number): Observable<any> {
    console.log('in service ')
    return this.http.request('GET', this.appConfig.apiEndpoint + '/Post/DownloadFileForManager/' + id, { responseType: 'arraybuffer' });
  }

我的打字稿代码:

DownloadImage(id: number): Observable<any> {
this.postService.downloadImage(id).subscribe(data => {
  const arrayBufferView = new Uint8Array(data);
  const blob = new Blob([arrayBufferView], { type: 'image/jpeg' });
  const urlCreator = window.URL;
  const imageUrl = urlCreator.createObjectURL(blob);
  this.image = this.sanitizer.bypassSecurityTrustUrl(imageUrl);
})
return this.image;
}

这是我的 HTML 代码:

    <ng-container matColumnDef="thumbnail">
            <th mat-header-cell *matHeaderCellDef> {{ 'GENERAL.PHOTO' | translate }} </th>
            <td mat-cell *matCellDef="let element">
                <img class="table-user-pic"
                    [src]="DownloadImage(9)"
                    id="photo"
                    alt="user avatar" width="50">
            </td>
        </ng-container>

现在当我发送请求时,它会向服务器发送许多请求。

我有 4 件商品,但它发送了 firstImage 4 次和接下来的 8 次。

有什么问题?这个问题怎么解决???

【问题讨论】:

  • 你在哪里调用DownloadImage方法?
  • @Prera​​kSola 我编辑问题。在[src]
  • 当您使用for 循环时,您可以执行以下操作:stackoverflow.com/a/40799136/4350275src 中调用方法确实是个坏主意。

标签: javascript angular typescript


【解决方案1】:

我想我听说 Angular 可以多次调用方法。如果您在组件的 init 方法中调用 downloadImage,则可以使用绑定来访问 this.image。

<img class="table-user-pic"
                    [src]="image"
                    id="photo"
                    alt="user avatar" width="50">

(但是,如果您可以通过 url 直接访问服务器中的图像,而不是流和 blob,则可以更多地利用浏览器中的现有功能。但在您的情况下这可能是不可能的)

【讨论】:

  • 它在表中。我有物品
  • 啊哈。但是尝试绑定它可能会减少调用服务器的次数。事情在循环中发生。并且您应该避免从 html 标记调用组件中的方法。
  • 我需要调用函数。我通过动态 id
  • 当您从服务器获取 i 时,我希望表中的每一行数据都有一个名为 ex: element.imageUrl 的属性。服务器可以在发送之前计算 url。然后你可以将它绑定到图像:[src]="element.umageUrl"。但我理解的她并非如此。相反,您可以在获得“循环数据”后使用 rxjs 来获取所有图像。图像可以设置为另一个集合。 [src]="图像[索引]"。最好在 init 方法中进行服务器调用。
  • 我无法直接访问图像。它向我发送了一个文件,我需要将其转换为显示图像
猜你喜欢
  • 2014-01-23
  • 2021-04-14
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-20
相关资源
最近更新 更多