Ad

Send Too Many Request To Server When Need To Get Image With Image

- 1 answer

I want to get image from server in Angular 7 with blob. I wrote this service for send request:

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

My Typescript code:

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;
}

This is my HTML code:

    <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>

now when i send the request it send many request to server .

i have 4 item but it send for firstImage 4 time and for next 8 time .

whats the problem ? how can i solve this problem ???

Ad

Answer

I think I heard that methods can be called by Angular a lot of times. If you call the downloadImage inside the init method of the component, you could access this.image with a binding instead.

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

(But if you could access the images in the server through a url directly, instead of streams and blob, you could make more use of the existing features in the browsers instead. But this might not be possible in your case)

Ad
source: stackoverflow.com
Ad