【发布时间】: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方法? -
@PrerakSola 我编辑问题。在
[src] -
当您使用
for循环时,您可以执行以下操作:stackoverflow.com/a/40799136/4350275 在src中调用方法确实是个坏主意。
标签: javascript angular typescript