The value is successfully stored in the component.ts file but is unable to be displayed on the

After successfully retrieving data and logging it in the console of the component.ts file, I encountered an issue where the data is not displaying on the template. My goal is to present the data in a table, but for now, I am attempting to show it within a

TAG

.

import { Component, OnInit } from '@angular/core';
import { CosterService } from 'projects/tradefigure-lib/src/lib/pages/blinkcoster/coster.service';

import { FormBuilder,FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { commodity, ICommodity } from 'projects/tradefigure-lib/src/lib/pages/blinkcoster/ICommodities.schema';

import { CrudtableService } from '../crudtable.service';

@Component({
  standalone: true,
  imports: [
   CommonModule,
   FormsModule,
   ReactiveFormsModule,
  ],
  selector: 'app-commodity',
  templateUrl: '
  
  ',
  styleUrls: ['./commodity.component.css']
})
export class CommodityComponent implements OnInit {
  // commodity: commodity = new commodity(); 
  commodity$!: ICommodity[];

  commoditys = this.commodity$
 
  isEditing: boolean = false
  title = 'crud';
  commodity: ICommodity [] = []
  constructor(
    private fb: FormBuilder, 
    private CosterService: CosterService,
    private crud: CrudtableService,
) { }

ngOnInit(): void {
  this.form;
  this.crud.getAll().subscribe({
    next: (res) => {
      this.commodity 
      console.log(res)
    }
  })
}
<div *ngFor="let commodity of commodity$ ">
  <p>{{commodity.offtalkerpriceOID}}</p>
  <p>{{commodity.commodityDescription}}</p>
  <p>{{commodity.unitPrice}}</p>
  <p>{{commodity.unitOfMeasure}}</p>  
</div>

I have attempted passing the data as an observable and utilizing the async pipe on the template without success.

The data is alerted and logged in the console, however, when using *ngFor to display it on the template, the template remains white.

If you have any solutions to this problem, please advise. Thank you!

Answer №1

It appears that the issue lies within the ngOnInit code block without further context.

The problem seems to be related to not correctly assigning the response value to the variable, causing it to show in the console (console.log(res)) but not reflect in the HTML (where this.commodity was used without assignment).

ngOnInit(): void {
  this.crud.getAll().subscribe(res => {
    this.commodity = res
    console.log(res);
  })
}
----------

There are two solutions to address this issue based on whether you prefer using the async pipe or not.

In both cases, the root cause remains linked to assignments in the ngOnInit method.

  1. Using the async pipe:

TS code:

export class CommodityComponent implements OnInit {
  commodities$: Observable<ICommodity[]>;

  ngOnInit(): void {
    this.commodities$ = this.crud.getAll();
  }
}

This assigns the observable returned by this.crud.getAll() to the variable commodities$. The template uses the

HTML code:

<div *ngFor="let commodity of (commodity$ | async)">
  <p>{{commodity.offtalkerpriceOID}}</p>
  <p>{{commodity.commodityDescription}}</p>
  <p>{{commodity.unitPrice}}</p>
  <p>{{commodity.unitOfMeasure}}</p>  
</div>

The async pipe handles the subscription for us.

  1. Without the async pipe.

TS code:

export class CommodityComponent implements OnInit {
  commodities: ICommodity[] = [];

  ngOnInit(): void {
    this.crud.getAll().subscribe(res => {
      this.commodities = res;
    })
  }
}

No need to manage the subscription since HTTP requests auto-complete upon completion.

HTML code:

<div *ngFor="let commodity of commodities">
  <p>{{commodity.offtalkerpriceOID}}</p>
  <p>{{commodity.commodityDescription}}</p>
  <p>{{commodity.unitPrice}}</p>
  <p>{{commodity.unitOfMeasure}}</p>  
</div>

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's the most efficient way to define the type of an object in TypeScript when one of its properties shares the same name as the type itself?

I'm currently working on processing an event payload where the event field is a string, and the content of data depends on the value of the event field. While I have come up with a representation that functions correctly, I can't help but feel th ...

Issue with webpack dev server not correctly generating output files to be included in index.html

Struggling to configure webpack and react with typescript without the complexity of CRA. The dev server isn't outputting files to index.html for viewing in the browser. I want to maintain a clean and simple structure, avoiding the multiple js scripts ...

After transitioning to standalone mode, Angular is unable to access the component before it has been

After diligently following the 3 steps to convert everything to standalone, all seemed well. https://angular.io/guide/standalone-migration#migrations-steps I proceeded to manually move the routes into the main.ts and utilized provideRouter as a provider ...

Establishing the root directory for imports in Angular 2

Currently, I am building an Angular2 application using version 2.0.0-beta.7 along with TypeScript. Initially, I had all my .ts files in a single directory for quick functionality access. However, now I am striving to reorganize them logically within a dire ...

Using regular expressions, replace all instances of " " with ' ' based on certain conditions

I am looking to replace quotes "" with single quotes '' within a string. string = `bike "car" bus "'airplane'" "bike" "'train'"` If a word is inside double quotes, it shoul ...

What is the process for unsubscribing from an Apollo Observable in an Angular application?

Currently, I'm in the process of constructing an angular (4.x) application with apollo-angular. One query that's been on my mind is how to properly unsubscribe from apollo observables, assuming it's even necessary. The approach I've ta ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

The ASP.NET Core 3.0 Web API method consistently encounters null values

I've encountered an issue with my Angular app where it displays a 500 server error. Here are the methods I'm using: /*Product Service*/ addNewProduct(newProduct: Product): Observable<Product> { console.log(newProduct); return this.http.po ...

Delay the Ngrx effect by 2 seconds before initiating the redirect

I have an ngrx effect that involves calling an HTTP method and then waiting for 2 seconds before redirecting to another page. However, the current behavior is that it redirects immediately without waiting. confirmRegistration$ = createEffect(() => { ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Encountering a challenge during the migration process from Angular 5 to Angular 6 in a .NET Core 2.1 project

We are currently using an angular SPA template and are encountering challenges during the migration from angular 5 to angular 6 in a .net core 2.1 project. As of now, I have updated all the necessary packages. Old version package.json { "name": "proje ...

Can React refs be safely accessed within a function wrapped with window.requestAnimationFrame?

My understanding of React and HTML rendering behavior is not complete, leaving me unsure about the possibility of a potential issue with React refs becoming null if accessed from a function wrapped in window.requestAnimationFrame. This function could be ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

Angular Resolver is producing a result of `undefined`

I'm encountering an issue in my Angular project where the resolve code is executing before the component can catch it, resulting in undefined data being returned. I am new to Angular and trying to implement a solution where the component only loads wh ...

The default value is not displayed in the Angular dropdown menu

When using regular html select menus, if you create an option element with selected and disabled attributes and provide text for that option, the text will be displayed by default in the select menu. Below is a basic example of HTML code: <select name= ...

Is *ngFor in Angular 4 causing extra unnecessary cycles?

Can you figure out the issue with this plunker where the counting starts at 5? http://plnkr.co/edit/n0qIlzG8TN1GXjtoFA8y?p=preview <div *ngFor="let joke of jokes"> <p>{{inc()}} - {{joke}}</p> </div> ...

Implementing a stand-alone column filter that seamlessly integrates with the dynamic features of an ngx datatable in Angular versions 4 or 5 without

Hey there! I'm new to Angular and currently working on Angular 4 and 5. I've been tasked with implementing customized column-based filters for the ngx datatable. I've made some attempts to do this in my ts, html, and scss files. Here's ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

Managing a project with multiple tsconfig.json files: Best practices and strategies

I've got a project structured in the following way: \ |- built |- src |- perf |- tsconfig.json |- typings |- tsconfig.json My main tsconfig.json looks like this: "target": "es6", "outDir": "built", "rootDir": "./src", Now, I need to have a ...

The number entered will be incorporated into the API URL key value by passing the variable from page.html to services.ts

Recently diving into the world of Ionic, Angular, and Typescript, I've had a burning question. Can the number inputted be added to the API URL as one of the key values? I came across this helpful guide, specifically focusing on key event filtering (wi ...