Difficulty encountered when converting objects into an array of a model within Angular

Below you will find the service code that I am using:

export class ProductListService {

  constructor(private httpClient: HttpClient) {

  }
  getProducts(): Observable<IResponse> {
    return this.httpClient.get<IResponse>('https://localhost:7127/Product/GetProductList');
  }
}

In addition, here is the component I have implemented:

  getProducts(): void {
    this.productsService.getProducts()
      .subscribe((response: IResponse) => {
       this.products = <Product[]>response.data;
      })
  }

The models for Product and IResponse are defined as follows:

export interface Product {
  Id: string;
  Title: string;
  Description: string;
  ImageUri: string;
  CategoryId: string;
}

export interface IResponse {
  data: object;
  status: number;
}

When retrieving data from the API, it returns a structure like this:

{
   "data": [
      {
         "id": "e15",
         "title": "LED TV 42 inch ",
         "description": "-",
         "imageUri": "C:\\wwwroot/cdn\\e15.jpg",
         "categoryId": "tv"
      },
      {
         "id": "e16",
         "title": "LED TV 52 inch ",
         "description": "-",
         "imageUri": "C:\\wwwroot/cdn\\e16.jpg",
         "categoryId": "tv"
      }
   ],
   "status": 200
}

To store this data in my products variable, how should I proceed?

Answer №1

I echo Sean Chase's sentiments. Adjust the casing of your model and consider converting the data property on the IResponse interface to Product[] (just a side note, interfaces typically don't start with I as per C# convention).

Are you utilizing the products property in the template HTML? If yes, you can employ the pipe async syntax and substitute the products property with an Observable<Product[]>. Here's an illustration

// models.ts
export interface Product {
    id: string;
    title: string;
    description: string;
    imageUri: string;
    categoryId: string;
}

export interface IResponse {
    data: Product[];
    status: number;
}



// product-list.component.ts
import { Component, OnInit } from '@angular/core';
import { map, Observable, of, Subscription } from 'rxjs';
import { IResponse, Product } from './models';
import { ProductListService } from './products-list.service';

@Component({
    selector: 'product-list',
    template: `
        <div *ngFor="let product of products$ | async">
            <div>Id: {{ product.id }}</div>
            <div>Title: {{ product.title }}</div>
            <div>Description: {{ product.imageUri }}</div>
            <div>CategoryId: {{ product.categoryId }}</div>
        </div>
    `
})
export class ProductListComponent implements OnInit {
    products$: Observable<Product[]> = of([]);

    constructor(private productsListService: ProductListService) {}

    ngOnInit() {
        this.products$ = this.productsListService.getProducts().pipe(map((res: IResponse) => res.data));
    }
}


// product-list.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { IResponse, Product } from './models';

@Injectable({
    providedIn: 'root',
})
export class ProductListService {
    // constructor(private httpClient: HttpClient) {}

    getProducts(): Observable<IResponse> {
        // return this.httpClient.get<IResponse>('https://localhost:7127/Product/GetProductList');
        return of({
            data: [
                {
                    id: '1',
                    title: 'title-1',
                    description: 'description-1',
                    imageUri: '/images/image-1.jpg',
                    categoryId: '1'
                } as Product,
                {
                    id: '2',
                    title: 'title-2',
                    description: 'description-2',
                    imageUri: '/images/image-2.jpg',
                    categoryId: '2'
                } as Product,
            ],
            status: 200
        });
    }
}

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

Using Python to generate a JSON file containing a list of artifacts through a loop

My file_list variable contains a list of files (artifacts), although it has been shortened for this example. print(type(file_list)) <class 'list'> print(file_list) ['file_AA.txt', 'file_BB.txt', 'file_CC.txt', ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Reduce the use of if statements

Is there a way to optimize this function by reducing the number of if statements? The currentFeatures are determined by a slider in another file. The cost is updated if the currentFeatures do not match the previousFeatures, and if the user changes it back ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

The jquery methods might encounter an issue with an undefined object

I have been attempting to implement a function that triggers when the user reaches the bottom of the window, but TypeScript is flagging errors and mentioning potential undefined objects related to window.scrollTop(), height(), and document.height(). Even ...

Utilizing a variety of Angular modules within Asp.Net Core

What is the optimal way to utilize multiple Angular 4 modules within the context of Asp.Net Core MVC? I am working on an application with various sections, each managed by a controller and view. Within these sections, I aim to incorporate sub-sections usi ...

Convert a collection of objects into a structured object containing arrays using the power of jq

I am looking to utilize jq in order to transform an array of objects into an object of arrays. If we take into account the following two files: file1.json: { "key1": 5, "key2": 10 } file2.json: { "key1": 2 } The goal is to combine them and crea ...

Two paths for a single Angular component

Is it feasible to create two distinct routes that reference one component? Consider the following scenario: { path: 'login', component: LoginComponent }, { path: 'user/:id/login', component: LoginComponent } I'm inquiring about t ...

Obtain every definition for a specific word in JSON format

Is there a way to retrieve all the meanings of a word in JSON format without requiring a key, signing up, or using an API key? For example, if I type in "test," I want to get all the definitions for that word. I attempted the following: but it did not wo ...

Streamlined conversion of JSON data to and from numerous small files

As I have a large list containing millions of small records in the form of dictionaries, my aim is to avoid serialized the entire list into a single JSON file. Instead, I am looking to write each record to its own separate file. When needed, I will then re ...

The MongoDB connection in NextJS 14 is causing a delay in loading the page

Occasionally, when trying to open a page through the dashboard menu, nothing happens on the frontend. There's no loading screen or any indication that the page is being loaded. How can this problem be prevented so that the page loads as intended? This ...

Utilizing PHP to parse JSON data and showcase the output

I'm currently facing an issue with parsing the data set that I have shared on pastebin at this link http://pastebin.com/TmZGw92j While I am able to navigate through routings, I seem to hit a roadblock when trying to go deeper into the data. Below are ...

Execution of the RxJS pipe Finalize operator initiated prior to Observable finalization

After updating the detailed information of users, I attempted to retrieve the updated user list. Initially, I used this.mediaService.updateImports(): Observable<any> to update the user details. Next, I tried displaying the updated user details us ...

Error message: "An issue occurred in Android where a java.lang.String value in the result cannot be converted to a JSONArray."

I followed the instructions in this link to implement JSON RPC. The response I receive is as expected, but I encounter a JSON error when attempting to parse it. This is my code: JSONEntity entity = new JSONEntity(jsonRequest); HttpPost request = new ...

Angular mat-table experiencing issues with matToolTip functionality

My Angular project is using Angular Material 16x, but for some reason, the matToolTip is not displaying at all. I have experimented with various versions, including a basic matTooltip="hello world", but I just can't seem to get it to work. I have come ...

Struggling to tally the entries and authenticate logins within Ionic 3 and Angular

In my application, users register by providing their email and password, which is then stored in a SQLite database. When the user attempts to log in using the same credentials, they should be redirected to the home page upon successful login. I am facing ...

Deciphering the evolution of APIs and managing internal API systems

I'm currently exploring the world of APIs and I have a few questions that are puzzling me. Question1: I understand that APIs facilitate communication between different applications. But why would a company need an API for internal use? For example, i ...

Parsing a JSON array containing objects with numerical keys in ASP.NET - A step-by-step guide

I've been working on an ASP.NET project and I’m dealing with a JSON array sent from the client in this specific format: [ {"1": "value1"}, {"5": "value2"}, {"10": "value32"} ] My goa ...

Unable to retrieve data with $.getJSON

I've hit a roadblock in finding the answer, so I created a temporary workaround - but unfortunately, it's not usable in the final file. Interestingly, when the JSON array is directly embedded in my JavaScript file, everything functions as expect ...