Obtaining images from the backend within a component's TypeScript file in a MEAN stack application is a

In my component.ts file, I am looking to retrieve images from the backend/images folder as Image objects. The paths of these images are stored in the 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 have attempted to fetch the images using an http request.

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


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

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

The 'images' array consists of files. The issue arises when http.get returns a blob string and core.js displays the 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

Answer №1

In order to properly handle the response, it is necessary to parse it as a blob rather than as a json

this.httpClient.get<Blob>(this.editImagePaths[i], {responseType: 'blob'})
    .subscribe(data => this.imageData.push(data));

Answer №2

When it comes to storing images in your database, the method you choose will impact how you access and display them later on. It's recommended to store the path to the image rather than as a blob, so that you can easily upload the image to a server folder.

If you have stored the image path, you can simply retrieve it from the server using a regular get or post request in Angular.

export class ProductComponent{

products: any;

constructor(
 private productService: ProductService
){}

this.productService.getProducts().subscribe(data => {
  this.products = data;
})

}

In addition, consider using a single variable to store all relevant product information, such as category and images. You can then loop through the image paths array in your component.html file to display them.

<img *ngFor="let image of products.imagePaths" [src]="image">

In summary, pay attention to how you store and retrieve your data, as it can greatly affect the efficiency and organization of your application. Stick to a consistent pattern, like storing image paths in an array, for easier access and manipulation.

Answer №3

Consider switching the responseType to 'blob'

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I need guidance on how to successfully upload an image to Firebase storage with the Firebase Admin SDK

While working with Next.js, I encountered an issue when trying to upload an image to Firebase storage. Despite my efforts, I encountered just one error along the way. Initialization of Firebase Admin SDK // firebase.js import * as admin from "firebas ...

Javascript is handling the JSON Request flawlessly, however, when using Nodejs, an error is encountered with a status

I'm trying to fetch a simple JSON File in NodeJS. Using Javascript and jQuery, it functions perfectly: $(document).ready(function() { $.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) { if ...

React Native is throwing an error message saying that the Component cannot be used as a JSX component. It mentions that the Type '{}' is not assignable to type 'ReactNode'

Recently, I initiated a new project and encountered errors while working with various packages such as React Native Reanimated and React Navigation Stack. Below is my package.json configuration: { "name": "foodmatch", "version ...

Using Sequelize to Create/Post Data with Many-to-Many Relationship

I've been exploring how to implement a M:N Association using Sequelize. After examining the documentation (doc), I came across a solution that closely matches my requirements: User.belongsToMany(Profile, { through: User_Profile }); Profile.belongsToMa ...

Angular 5: Issues with retrieving response using HttpClient's get request

Alright, so typically I work with Angular 1.*, but I decided to dive into Angular 5 and man, it's been a bit of a challenge. It feels unnecessarily complex, but oh well... So I'm trying to make an HTTP call, and I have this node API that is retu ...

Messages sent to RabbitMQ through amqplib are not being received in the reply queue, even after being processed by NestJS

Currently, I am utilizing NestJS (v8) in combination with the RabbitMQ transport (Transport.RMQ) to receive messages. The code structure within my NestJS application appears as follows: // main.ts const app = await NestFactory.createMicroservice<Micro ...

Experience the latest happenings in SAP Spartacus 4.0 by signing up for updates directly from

I am facing an issue while trying to register an event in Spartacus import { Injectable } from '@angular/core'; import { CartDetailsComponent, PromotionService} from '@spartacus/storefront'; import { ActiveCartService, SelectiveCartServ ...

Can you provide a guide on setting up and utilizing mathlive within NuxtJS?

Can anyone assist me? I am trying to figure out why my code is not working or if I have implemented it incorrectly. I used npm i mathlive to obtain input. However, following the instructions for implementing nuxt plugins in the documentation has not yield ...

Command prompt fails to recognize Gulp despite the inclusion of an updated path variable

Following the standard gulp installation procedure, I first executed: $ npm install --global gulp-cli Then, as per instructions, added gulp as a dev dependency to my project: $ npm install --save-dev gulp A gulpfile.js was also included in the project ...

Anguar 9 is experiencing issues with loading datatable pagination, search, and sorting functionalities

My problem lies in the pagination, search, and sorting functions not loading properly in my data table despite the data binding correctly. I have provided my html, component, and service files for reference. .html <table class="table table-striped ...

What is the best way to bring a local package into another npm package and verify its functionality using Typescript?

In a scenario where there are 3 npm projects utilizing Webpack and Typescript, the folder structure looks like this: ├── project1/ │ ├── tsconfig.json │ ├── package.json │ ├── src/ │ │ └── index.ts │ ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

The Apache Cordova application developed in Visual Studio 2015 is experiencing technical difficulties

When attempting to run my first Apache Cordova app in Visual Studio 2015 on Windows 8, I encountered an error. Despite trying some solutions, such as cleaning the Cordova cache in the options menu, the error persisted. Below is the error message that needs ...

When using `useSWR`, it will return { null, null } for a successful request

When attempting to query the Firebase real-time database using useSWR in my next.js project, I encounter a perplexing issue where both the data and error variables always return as null. import useSWR from 'swr'; const LastSales: NextPage = () = ...

Destructuring an object in the find method using TypeScript

I'm running into an issue with object destructuring: Property 'name' does not exist on type 'ItemType | undefined'.ts(2339) App.tsx import "./styles.css"; type ItemType = { id: number; name: string; }; export defaul ...

The Kendo-datepicker always excludes the number zero in the day section

When I try to enter the date: 5/01/2017 The first zero in the days section is always missing when using kendo-date-picker, resulting in the following date: 5/12/17 In my HTML code: <kendo-datepicker [min]="min" [max] ...

It is not possible to bind an attribute to an element that already has a Bootstrap class applied to it

Currently, I am working on an Angular 2 web application and incorporating bootstrap for styling purposes. Within the app, there is a small triangle that needs to alternate between being visible and invisible. Here is the code snippet representing this elem ...

React Router Issue: Component Not Rendering When <nav> Element Is Incomplete

I am currently experiencing an issue with rendering a component in my React TypeScript application using React Router. The problem arises when trying to navigate to the AddTask component by clicking on a link within a <nav> element. Strangely, the co ...

Using NodeJS and ExpressJS to send the HTTP request response back to the client

After creating a website using Angular 2 and setting up node.js as the backend, I successfully established communication between the Angular client and the node.js server. From there, I managed to forward requests to another application via HTTP. My curren ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...