Transfer information between different classes and proceed to loop through the updated class directly from the html webpage

The Scenario

In my angular 7 application, I am fetching data from a web API in JSON format. The app is functioning correctly, but I believe I am making excessive API calls and can optimize it to just one call.

Custom Class:

    export class customClass {
        constructor(tagname: string, value: number, description: string, units: string, quality: string, timestamp: string, lowlimit: number, highlimit: number, asset: string) {
            this.tagname = tagname;
            this.value = value;
            this.description = description;
            this.units = units;
            this.quality = quality;
            this.timestamp = timestamp;
            this.lowlimit = lowlimit;
            this.highlimit = highlimit;
            this.asset = asset;
        }
        tagname: string;
        value: number;
        description: string;
        units: string;
        quality: string;
        timestamp: string;
        lowlimit: number;
        highlimit: number;
        asset: string;
    }

dashboard.component.ts - within this file, there is an array of type customClass.

mylist: customClass[];

The array is populated within the ngOnInit using:

this._myService.getcurrentvalues()
      .subscribe
      (
        (data: customClass[]) => this.mylist= data

      );

Then, I display this array in the HTML component using:

<mat-card-content *ngFor="let com of myList">

This allows me to generate a line of text per entry in the list by referencing properties such as:

<p class="tag-description">{{com.description}}</p>

The Objective

I realize that I am calling the API multiple times for a single HTML component. To address this, I want to fetch all the data with a single API call and then manipulate it within the application for better performance.

The Challenge

To achieve this, I attempted to create a function in my dashboard.component.ts file which I could then iterate through in my HTML component. I intended to place this function outside of ngOnInit. Here is what I tried:

  get myData(){
      let result : customClass[];

    for(var item of Object.keys(this.myList)){

         let item1 = this.myList[item]
         for(var item2 of item1){
           if (item2.asset == "someString")
           {
             var newObject : historiantags;
             newObject.tagname = item2.tagname;
             newObject.value = item2.value;
             newObject.description = item2.description;
             newObject.units = item2.units;
             newObject.quality = item2.quality;
             newObject.timestamp = item2.timestamp;
             newObject.lowlimit = item2.lowlimit;
             newObject.highlimit = item2.highlimit;
             newObject.asset = item2.asset;
             result.push(newObject);
           }
         }
     }
     return result;
  }

Trying to display this in my HTML component using:

<mat-card-content *ngFor="let com of myData">

However, this setup resulted in the error:

item1 is not iterable

Is there a way to make this work or should I approach it differently?

*Update

To troubleshoot, I added the word debugger to the myData function, but it was never triggered. Additionally, adding {{com | json}} to the HTML did not return anything, indicating that myData() is not being called. How can I ensure that this function is executed?

Answer №1

Have you considered utilizing a tool like JsonConvert available at https://www.npmjs.com/package/json2typescript? It can help simplify the conversion of JSON data in your getcurrentvalues method as shown below:

getcurrentvalues(): Observable<myClass[]> {
   return this.http.get('Your URL HERE')
     .pipe(
        map(response =>
          new JsonConvert().deserializeArray(response, myClass)
        )
   );
}

Then, in your component, you can use:

myList$: Observable<myClass[]>;

ngOnInit(){
  this.myList$ = this._myService.getcurrentvalues();
}

Finally, in your HTML template:

<mat-card-content *ngFor="let com of myList$ | async">

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 process of incorporating a custom data type with ngModel in Angular Dart?

In the process of developing an app using AngularDart, I have come across some interesting challenges. While I appreciate the ease with which forms can be handled in AngularDart, I am facing a hurdle when it comes to working with different data types. My ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

React throwing a typescript error while attempting to update state based on the previous state

Hello there! I'm fairly new to working with TypeScript and I've encountered an issue with a piece of state in a child component. I'm trying to modify it based on the previous value, but every time I call the setState function, I get a type e ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...

Created computed getter and setter for Vue models (also known as "props") using the syntax of Vue Class Component

After exploring the limitations of v-model in Vue 2.x in this Stack Overflow thread, I discovered a way to connect parent and child components using v-model. The solution proposed is as follows: --- ParentTemplate: <Child v-model="formData"> ...

Tricks to access value from a Nativescript array of Switch elements when tapping a Button

Scenario: In my project, I am using Nativescript 5.0 with Angular. The data is fetched from an API and displayed in customers.component.ts I am successfully rendering the elements based on the received IDs in customers.component.html When the user inter ...

Presenting SQL information in a hierarchical Angular grid for easy visualization

As a newcomer to Angular, I have a requirement to display data in a multilevel/hierarchical Angular Grid. The data is retrieved from a SQL Database using a query with arguments provided in the where clause. Some questions that come to mind are: Is there ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

How to load several stylesheets for a component in Angular 2

Struggling with my angular2 application, I encountered an issue when attempting to load multiple stylesheets for the same component. Below is a snippet of the code: import { Component } from '@angular/core'; @Component({ selector: 'my-tag& ...

Having trouble correctly initializing RequestOptionsArgs for a POST request in the service function

Recently, I have been working with Angular 6 and decided to follow a helpful video tutorial on image submissions (link to the video). My goal is to track the progress of the form submission in order to display the percentage of the uploaded file. In my c ...

Trouble with displaying cell content in ag-grid within an Angular application

I have implemented ag-grid in my Angular project and I am trying to redirect to a link when a specific cell is clicked. Currently, I have a new value coming from an API which is nested inside an object in an array. For example, the object is dto-> dat ...

What could be causing the lack of reflection of Angular changes in the browser post-build process?

I'm having trouble seeing changes reflected in my Angular project after making them. I've tried clearing the cache pages and cookies in Chrome, as well as enabling disable cache in the network tab of developer tools. In addition, I cleared the a ...

Use the res.json method in express.js to automatically generate a predefined response structure

I'm looking for guidance on how to properly use res.json in my code. I want to establish a default response structure that includes a message and error, while also being able to include additional data when necessary. For example, when I use res.statu ...

Any ideas on troubleshooting the NG0100: ExpressionChangedAfterItHasBeenCheckedError issue and resolving it?

I have encountered NG0100: ExpressionChangedAfterItHasBeenCheckedError in Angular, and it seems to persist despite my efforts in my scenario. Essentially, within the interceptor, I have a service that loads a boolean value representing "status": interce ...

The Angular translation service may encounter issues when used on different routes within the application

I'm currently working on an Angular application that has multi-language support. To better organize my project, I decided to separate the admin routes from the app.module.ts file and place them in a separate file. However, after doing this, I encounte ...

Is there a method in TypeScript to retrieve property names from an interface resembling reflections in C#?

I am working with an interface in TypeScript/Angular that has various properties. I'm curious if there is a way to access the property names within the code. Here's an example of what my interface looks like: export interface InterfaceName ...

Typescript - Keeping a log of object keys along with their corresponding key type values

Imagine having the following scenario where you need to create an object with keys that are transformed versions of the original type's values: export type CCDTypes = { AuthorisationCaseEvent: AuthorisationCaseEvent, AuthorisationCaseField: Author ...

When selecting an ion-tab-button in Ionic 4, the color does not change as expected

One of my challenges involves implementing an ion-tab that allows different ways of redirection: either through Routes specified in the tabs.module.ts file or by using [routerLink] directly in the HTML. The issue I am facing is that when the ion-tab-butto ...

Assistance is not aligned

I have a service that is utilized for making calls to a webapi. The webapi URL is fetched from a local json file. An issue arises where the service method ends up calling the incorrect webapi URL, and it seems likely that this happens because the methods ...

Refused to run script from inline content on the lightweight server due to security policy restrictions

I have been adhering to Angular's best practices in order to create a Progressive Web App (PWA). After building the production version (ng build --prod --aot), I am running it from the dist folder on localhost using npm run dev ("dev": "lite-server"). ...