1
votes

I need to get images from backend/images folder as Image object in component.ts file. I can get the path of the image from database.

this.productsService.getProduct(this.editId).subscribe(productData => {
    this.name = productData.name;
    this.code = productData.code;
    this.category = productData.category;
    this.description = productData.description;
    this.details = productData.details;
    this.editImagePaths = productData.imagePaths;
  });

I tried get the images via http request.

for (let i = 0; i < this.editImagePaths.length; i++) {


      this.http.get<File>(this.editImagePaths[i]).subscribe(value => {

        this.images.push(value);
      });
    }

images is an array of File type. The problem is http.get returns blob string and core.js gives following error;

core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:3000/images/asd0-1575503057766.png", ok: false, …} error: {error: SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse () at XMLHtt…, text: "�PNG ↵↵ IHDRI������PLTE�F���+*)…�LЙ�3 @��I�؈�ݝ�y�(pIEND�B`�"} headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:3000/images/asd0-1575503057766.png" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:3000/images/asd0-1575503057766.png" proto: HttpResponseBase

3
Your content type is probably application/json instead of something like image/png. Try doing it in postman or something to narrow down your issues. (Take angular/HttpClient out of the picture)mwilson

3 Answers

1
votes

You need to parse the response as a blob and not a json

this.http.get<File>(this.editImagePaths[i], {responseType: 'blob'})
    .subscribe(value => this.images.push(value));
0
votes

Firstly, it depends on how you stored the image either as blob or the URL/path in your database. however, i recommend storing the path to the image, while uploading the image to a folder on the server.

Now if a path, just get the path to the image on the server with normal get request or post request in angular.

export class ComponentName{

products: any;

constructor(
 private service: ServiceComponent
){}

this.service.productList(values).subscribe(data => {
  this.product = data;
})

}

also, if you noticed how i used one variable to store all the data; category, images, and others. now if i want to show my image i will do like so in my component.html

<img *ngFor="let images of product.imagePaths" [src]="images">

in conclusion, check how you store you data and how you send back your data. it maters. my pattern stores just image path, even though in an array and retrives the images as json-array.....

0
votes

Try to change responseType to 'blob'

this.httpClient.get(imageList, { responseType: 'blob' }).subscribe(value => {
   this.images.push(value);
});