Angular 13 displays an undefined http response in network presentations

I'm facing an issue while trying to retrieve products from the NestJS server. Although I am able to fetch the products, the attached images are not displaying. Based on some suggestions from Stack Overflow, it seems that I need to convert the incoming images into their respective formats. However, the problem lies in the fact that I am receiving a complete list of objects instead of just images. To address this, I attempted to extract the images from the data subscribed using the map function. After implementing a conversion logic, I encountered undefined in the Network Panel.

In the screenshot below, you can observe the presence of undefined with text/html type response in the Network tab. Beneath this information, all image paths are visible in the console panel.

https://i.sstatic.net/4G69j.png

In my service.ts file, when setting responseType:'blob' for the get method, I encountered an error, so I refrained from utilizing blob

public getallbooks(): Observable<any> {
    return this.httpclient.get(
      `${this.API_SERVER}/books`
      //  {
      //   responseType: 'blob',
      // }
    );
  }

The component.ts file contains the function for converting images and displaying the product

  image!: any;
  results?: Book[];

ngOnInit() {
    this.apiService.getallbooks().subscribe((data: Book[]) => {
      this.results = data;
      const arr = this.results?.map((i) => {
        return i.coverimage;
      });
      this.createImageFromBlob(arr);
      console.log(this.results);
      console.log(arr);
});
 }
createImageFromBlob(image: any) {
    let reader = new FileReader();
    (reader.onload = () => {
      this.image = this.sanitizer.bypassSecurityTrustUrl(
        reader.result as string
      );
    }),
      false;
    if (image) {
      reader.readAsDataURL(new Blob([this.image]));
    }
  }

Below is the HTML code snippet for rendering the images

<div class="grid" *ngFor="let result of results">
      <div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
        <img
          class="image"
          [src]="'http://localhost:3000/' + image | safeurl"
          alt=""
          height="400px"
          width="250px"
          style="border: 1px solid red"
        />

Answer №1

In my situation I had a collection of books with each book having a designated path for its image. Utilizing the ngFor directive, I set the src attribute of the image to the respective path. While this approach seemed correct, the images were not appearing and the Network revealed that they were being recognized as text/html type. The underlying issue here was not the file type, but instead stemmed from the structure of my URL. Within my NestJs server, I had an assets folder located at the root directory, and in my code for handling file uploads in NestJs, I specified the image paths using ./assets/. This configuration typically allows me to view the images in the browser via links like

http://localhost:3000/imagename.png
, indicating that my server is configured to serve images over the root URL. However, my API returned URLs containing ./assets/, causing discrepancies.

<div *ngIf="image">
          <img
            class="image"
            [src]="'http://localhost:3000/' + image | safeurl"
            alt=""
            height="400px"
            width="250px"
            style="border: 1px solid red"
          />
        </div>

Initially, I believed that I accessed the URL as such:

http:localhost:3000/imagename.png
, utilizing the safeurl pipe to ensure security. However, Angular interpreted the URL as
http:localhost:3000/./assets/imagename.png
, revealing an incorrect format due to the presence of extra characters (., ,). Furthermore, since my server was set at root, the URL
http;//localhost:3000/assets/imagename.png
was also erroneous. Note that content stored at the root can be directly accessed after the server's port number, following the pattern
http://localhost:YourServerPortNumber/TheThing_Set_at_Root
.

The solution to this dilemma entails:

src="http://localhost:3000/{{
              result.coverimage.replace('./assets/', '')
            }}"

Additionally, modify the code snippet as follows:

<div *ngIf="result.coverimage">
          <img
            class="image"
            src="http://localhost:3000/{{
              result.coverimage.replace('./assets/', '')
            }}"
            alt=""
            height="400px"
            width="250px"
            style="border: 1px solid red"
          />
        </div>

By incorporating .replace('./assets/', ''), we effectively eliminate the unnecessary ./assets/ segment from the URL, resulting in a cleaner format like

http://localhost:3000/imagename.png
.

Temporarily removing the safeurl pipe for localhost may suffice, though it remains crucial for production usage or specific scenarios even within localhost environments.

Furthermore, the need for the createImageFromBlob() function and array manipulation methods like map diminishes, simplifying the process to display data:

ngOnInit() {
    this.apiService.getallbooks().subscribe((data: Book[]) => {
      this.results = data;
      console.log(this.results);
  });
  }

My interpretation and explanation should accurately reflect the aforementioned technical considerations.

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

Runtime not able to identify new modifications post migration from Angular 2 to Angular 6

I successfully upgraded my Angular 2 project with DotNetCore to Angular 6 by executing the following command: npm install -g npm-check-updates ncu -u After completing the migration process, I found that while I can still run my previously developed proje ...

Does the positive Z axis move inward in threejs? The behavior of camera.near and camera.far seems strange

My goal is to display only a slice of my 3D object. I have tried setting the orthographic camera's camera.near to 2.0 and camera.far to 1.5, then iterating with values of camera.near = 1.5 and camera.far = 1.0. However, this approach is not yielding t ...

Tips on incorporating character frequency counting in a string with JavaScript

I am working on a simple project involving HTML code. <textarea id="text" placeholder="Type text...."></textarea> <a id="button" class="button"></a> <textarea id="result" disabled></textarea> Additionally, I have a blo ...

Turn on/off the button click functionality on a jQuery smart wizard control

I am currently utilizing this particular control, which happens to be version 3 of jQuery Smart Wizard. Here is the code snippet for the smart wizard: $('#wizard').smartWizard({transitionEffect:'slide'}); These are some helper functi ...

Material User Interface, MUI, Modal, Back to Top Scroll按钮

After spending some time experimenting with scrollTop and the Dialog component (a fullscreen fixed modal) from Material-ui, I found that I couldn't quite get scrollTop to function properly. Whenever I clicked the "go down" button, it would either retu ...

Issue with JavaScript not executing upon clicking the submit button on a form within the Wordpress admin page

In the admin pages of my Wordpress installation, I have created an HTML form. My goal is to validate the data inputted when the submit button is pressed using a Javascript function. If the data is not correctly inserted, I want alerts to be displayed. Desp ...

Troubleshooting: Form submission not triggering AJAX using JQuery

I'm attempting to implement some AJAX rendering when the form is submitted, but for some reason it's not functioning correctly. Upon submitting the form, I am redirected to the submit page. Here is my JavaScript code: $('#knappen').cl ...

Troubleshooting problems with scrolling on JavaScript in Edge, Opera, and Chrome

Currently, I am developing a fun CSGO-inspired box opening feature on my food recipe website that randomly selects recipes for users. However, I have encountered some challenges with the scrolling functionality. It seems to be incompatible with certain bro ...

Inject various JavaScript data into different div containers

The issue at hand is quite straightforward. Here is a sample for displaying a single variable in a div with the "container" ID: let first = 5; document.getElementById('container').innerHTML = first; <div id="container"></div> How ...

Dynamic parameters in the Vue router

Struggling to find the right syntax for passing dynamic param data. Experimented with multiple approaches, but I thought I could pass someValue like this: <router-link :to="{ name: 'Foo', params:{ bar: ${someValue} } }"> Unfortunately, co ...

Ways to trigger the upgradeneeded event in IndexedDB without upgrading the version

Can you help me understand the "upgradeneeded" event? I want to be able to check the database every time a user reloads the page. Is there a way to trigger this without actually upgrading the version of the indexedDB? request.addEventListener('upgrad ...

Issue encountered after updating to Spartacus 3.0 from 2.0: Unable to access the 'findStores' property due to a TypeError

After upgrading to Spartacus 3.0 from 2.0, everything seems to be working fine except for this particular error that keeps popping up. I followed the steps provided by SAP team on the documentation site to add the storefinder module. https://i.sstatic.net ...

Is MongoDB still displaying results when the filter is set to false?

I am currently trying to retrieve data using specific filters. The condition is that if the timestamp falls between 08:00:00 and 16:00:00 for a particular date, it should return results. The filter for $gte than 16:00:00 is working correctly, but the $lte ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

Encountering a problem retrieving the .ClientID property in ASP.NET using C#

In my uploadError javascript function for AsyncFileUpload from AJAX toolkit, I have the following code snippet: function uploadError(sender, args) { document.getElementById("<%# uploadResult.ClientID %>").innerText = args.get_fileName(), "<sp ...

Error: The utilization of the life cycle interface mandates the implementation of type checking

Currently, I am in the process of translating my typescript project to Webpack 2. While one project transitioned smoothly, I encountered an error with the other project... Error: use-life-cycle-interface necessitates type checking After conducting a br ...

Utilizing a constant in setting the slotLabelFormat

I am attempting to configure the slotLabelFormat options in a React TypeScript project When I directly set slotLabelFormat={{ hour: "2-digit", minute: "2-digit", omitZeroMinute: false, meridiem: "short" }}, TypeScript compile ...

Updating class on elements in arrays

There are multiple elements, each with a unique ID "xxx_view_ch_&&&" within an outer div with the ID "xxx_view_&&&". The goal is to change the class of the element with the ID "xxx_view_ch_&&&" when the user clicks on the entire element ("xxx_view_&&&"). ...

Accept only numerical input, any other type will prompt a notification

Ensuring that users can only input numbers is functioning properly. If a user attempts to enter anything other than a number, an error message should be displayed. I have experimented with Validators and patterns, but I am unable to get the error message ...

How can one hand over a file to the http.write method in Node?

When I attempt to print a file using the res.write() method, I encounter an error: TypeError: First argument must be a string or Buffer This is my code snippet: var fs = require("fs"); var http = require("http"); http.createServer(function (req, res){ ...