The forEach method is not valid for Response

Seeking assistance with my Angular project - a beginner in programming looking for guidance on retrieving images from a web API.

  • ASP.NET Framework Web API 4.7
  • Angular CLI: 13.3.7
  • Angular: 13.3.11

On the Web API side:

Controller:

[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class HomeController : ApiController
    {
      // Code snippet here...
    }
    

Models:

HomeModel class:

// Code snippet here...
    

Motorcycle class:

// Code snippet here...
    

DTO class:

// Code snippet here...
    

On the Angular side:

Model:

home-categorised-bikes.model.ts:

// TypeScript code snippet here...
    

Service:

home-categorised-bikes.service.ts:

// TypeScript code snippet here...
    

app.component.ts:

// TypeScript code snippet here...
    

app.component.html:

<div class="container">
        <h4>{{title}}</h4>

        <div *ngFor="let bikeImg of bikesImgs">
            <img [src]="bikeImg">
        </div>
    

Swagger:

https://i.sstatic.net/Z1MRo.png

Error:

Response.forEach is not a function at AppComponent.onHomeBikesImgsResponse (app.component.ts)

Appreciate any help provided. Thank you.

Answer №1

Looking at the swagger screenshot provided, it's clear that your response does not consist of an array but rather a collection of objects such as streetBikes and sportBikes. Each of these objects contains a list of arrays.

In order to iterate through each property and consolidate all bike images into a single array, you can use the following code snippet:

function processBikeImages(response: any): void {
  for (const property in response) {
    response[property].forEach((item: ImageData) => {
      allBikeImages.push(`data:image/png;base64, ${item.image}`);
    });
  }
}

Answer №2

Your API is designed to return a single response of type HomeModel, rather than an array of HomeModel.

home-categorised-bikes.service.ts:

export class HomeCategorisedBikesService {

  imageUrl = 'https://localhost:44377/api/Home';

  constructor(private http: HttpClient) { }

  getImg(): Observable<HomeModel> {
    return this.http.get<HomeModel>(this.imageUrl);
  }
}

app.component.ts:

private processHomeBikeImagesResponse(Response: HomeModel): void {
  Response.sportBikes.forEach((img: FromDTOImgs) => {
    this.bikesImages.push(`data:image/png;base64,${img.image}`);
  });

  Response.streetBikes.forEach((img: FromDTOImgs) => {
    this.bikesImages.push(`data:image/png;base64,${img.image}`);
  });

  Response.adventureBikes.forEach((img: FromDTOImgs) => {
    this.bikesImages.push(`data:image/png;base64,${img.image}`);
  });

  Response.scooterBikes.forEach((img: FromDTOImgs) => {
    this.bikesImages.push(`data:image/png;base64,${img.image}`);
  });
}

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

What is the best way to divide text into key-value pairs using JavaScript?

I have data in text format from my Raspberry Pi that I need to insert into MongoDB as key-pair values or JSON for my Node.js Application. I'm relatively new to JavaScript and I'm looking for a solution. Any suggestions would be greatly appreciate ...

Tips for using a string as a generic type in TypeScript

Looking to create a flexible type that can transform existing types into ones that align with a specific API response structure. My goal is to take a variety of types and generate new types based on them, constructed as follows: // original type definition ...

Unable to retrieve response in this context. Display error message: Response.Write(ex.ToString());

Every time I launch my website, I encounter an error in the global.asax file. However, after refreshing the page, it works correctly. It's puzzling to me why this happens. An unhandled exception occurred during the execution of the current web reques ...

The nz-switch function is malfunctioning as a result of an update that has affected its value

<form [formGroup]="businessFoodHygieneForm"> <div class="box p-4 d-flex jc-between ai-center"> <span> Food Hygiene Link </span> <label> <nz-switch class="switch- ...

Token does not contain the necessary claim nbf (not before) for access while utilizing Firebase Microsoft Sign-in to retrieve data from MicrosoftGraph

I currently have a mobile application structured with Angular on the front-end and a Node.js server on the backend. We have successfully integrated Google Cloud's Identity Providers for users to sign in using Google and/or Microsoft accounts. While ...

Encountered an error in Angular Universal + PWA stating: { Error: Uncaught (in promise): Error: Unable to find a match for the routes. URL Segment: 'ngsw_worker.es6.js

I have successfully set up a universal and PWA app. Is there a solution to resolve this issue? You can check out a DEMO (the first push :) ) here SERVER SIDE CONSOLE ERROR { Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: &ap ...

While attempting to set up a fresh 'TypeScript Angular Project' in Visual Studio 2022, I encountered an Error Message stating "Visual Studio Code: Illegal characters found in the path"

Encountering an issue when attempting to create a new 'Standalone TypeScript Angular Project' called HealthCheck in VS 2022. Upon clicking the create button, I receive an Error Message stating "Visual Studio Code: Illegal characters in path" for ...

The document is failing to save through an HTTP request

I am having trouble saving a file to a directory within my solution and then storing the file path in the database as a string. The file does not seem to be saving to the directory, resulting in the path not being saved either. What could be causing this i ...

Optimizing Code in .NET: Consolidating Nested Using Statements into a Single Using Statement

Imagine you encounter some C# code with nested using statements and resources like this: using (var response = (HttpWebResponse)request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { using (var reader = new Bi ...

Angular: Utilizing httpClient to retrieve an object map and passing it as a return value in a function

I have a basic Angular application that retrieves data from a Spring-Boot backend. export class UserDto { constructor( public login: string, public password: string, ) { } } export class AuthService { private url = '....'; get ...

Adding or subtracting values in Angular framework to manipulate numbers

I am looking to increment a number from 1 to 50. I attempted to use the following code, but unfortunately the function is not working properly. See Demo Here Here is the HTML: <Button text="+" (tap)="plus()"></Button> <Button text="-" (t ...

Retrieve the name from the accordion that was clicked

Hey there, I have a simple accordion that is based on an API called "names". <div *ngFor="let item of showDirNames | async | filter: name; let i = index;"> <button class="accordion" (click)="toggleAccordian($event, i)&q ...

What is the proper way to utilize queries in BlitzJS?

I am attempting to extract data from a table by filtering based on the relationship with the Blitzjs framework. However, I am facing difficulties using queries as it seems to be the only option available. Every time I try to call the quer ...

IFrame issue: Page is constantly refreshing when on iframe source

Recently, I started working with asp.net and I'm attempting to call an Iframe src within a table row using a JavaScript click event. (i.e onclick="return loadPhaseWiseChart("DGSET00025");") Here is my code snippet: <tr height="25" id="row3" oncli ...

Is there a way to use Regex to strip the Authorization header from the logging output

After a recent discovery, I have come to realize that we are inadvertently logging the Authorization headers in our production log drain. Here is an example of what the output looks like: {"response":{"status":"rejected",&quo ...

Leveraging Typescript in Firebase Cloud Functions to effectively work with intricate interfaces

When querying a collection on the app side, I am able to automatically cast the result as an interface using Positions constructor that takes in interface IPosition. However, attempting to do the same on the cloud functions side prevents the functions fro ...

angular display message after delay

Is there a way to create a function that takes an error message string and automatically hides it after a certain amount of time? I want to have this function available throughout my application so I don't have to write the same code every time I rece ...

Is there a way to ensure that the transparency feature of a PictureBox works correctly even when it is placed on top of another PictureBox?

While working on a game project in Windows Forms, I encountered an issue that was bothering me. The new pictureboxes I added seemed to be "eating" away at the image behind them, showing the background of their parent instead. It turns out that this is how ...

How to retrieve the <script> tag using codebehind

While attempting to access < script type='text/javascript' ....>< / script > that already exists within the Head tag. This is how I tried to achieve it, foreach (Control ctrl in Header.Controls) { Resp ...

Transform the JObject from Newtosoft into a BsonDocument seamlessly

Looking to convert a JObject to a BsonDocument? Check out this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (since BsonWriter is obsolete, I'm using BsonDataWriter) var jObject = JObject.Parse("{\"name\":\"va ...