Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts

   import { Component, OnInit } from '@angular/core';

    @Component({

      selector: 'app-demo',

      templateUrl: './demo.component.html',

      styleUrls: ['./demo.component.css']
    })

    export class DemoComponent implements OnInit {

       product : Object[]

      constructor() { 

        this.product=[
          {
            id: "1",
            name :"tiger"
          },
          {

          id: "2",
          name :"loin"
          }
        ];
      }
    public getProducts(){
      this.product;
    }
      ngOnInit() {
      }

    }

demo.coponent.ts

<h1>

    <div *ngFor="let product of getProducts()">
        <p>{{product.id}}</p> 
        <p>{{product.name}}</p>

    </div>
</h1>

I am a beginner in Angular and I am facing an issue with the HTML code. I am unable to retrieve data from the function and I am getting error messages in the console.

However, when using the product variable directly, I am able to display the data:

<div *ngFor="let product of product">
        <h1>{{product.id}}</h1> 
        <h1>{{product.name}}</h1>

    </div>

Answer №1

To retrieve the data, make sure to utilize the return statement

function getProducts(){
   return this.products;
}

Answer №2

Try this out:

fetchItems = ()=> this.item;

Alternatively, you could simply include the return statement within the current function like so:

function fetchItems(){
     return  this.item;
}

I trust this will be beneficial.

Answer №3

In this particular scenario, there is no need to invoke a function from the .html file in order to retrieve data, and it is not advisable to do so. Your current approach is appropriate and can be continued as follows:

<div *ngFor="let product of products">
    <h1>{{product.id}}</h1> 
    <h1>{{product.name}}</h1>
</div>

You have direct access to the product array within the .html file, eliminating the necessity for an additional function to fetch the product array.

Additionally, remember to include a return statement in your function.

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

How to Force a jQuery Redraw Following Data Retrieval Using Ajax

Hey everyone, It's been a long time since I started listening, but this is my first post... I have a client who needs a complex feature on their website. They want to merge the content of 3 different pages into one seamless experience for users afte ...

AngularJS - Unusual outcomes observed while utilizing $watch on a variable from an external AngularJS service

Within the constructor of my controllers, I execute the following function: constructor(private $scope, private $log : ng.ILogService, private lobbyStorage, private socketService) { this.init(); } private init(){ this.lobbyData = []; this.initial ...

Utilizing TypeScript in an AngularJS (1.x) project alongside Webpack: A Step-By-Step Guide

Currently, I am working through the official guide on transitioning from AngularJS (1.x) to Angular (2+). I have successfully divided my application into Components and integrated ES6 with Webpack as the module loader. However, I now find myself unsure of ...

The mystery of the unassigned value in $(this).data(value) when using the jQuery click() method

In my Rails 5 application, I am working on creating a dynamic menu that will guide users to different parts of the site based on their location. The idea is that when they click on a specific menu item from the home page, a modal will appear allowing them ...

Tips for keeping components mounted despite changes in the path

How can I maintain state in React routes to prevent unmounting when switching between them? In my application, it's crucial to keep the state intact during route changes. When changing routes, the respective components mount and unmount. How can this ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

The "shape" property is not available while utilizing generics with toZod

Short version: I encountered a type error, and here is the link to the TS PLAYGROUND I am looking to ensure type safety when creating zod schemas. To achieve this, I define the data type like so: type Option = { id: number }; Using this type definition ...

What is the best way to accurately determine an element's location after scrolling to it?

I'm currently working on pinpointing the location of a specific element on a webpage once it has been scrolled to using JavaScript. Queries: How can I precisely determine the position of an element post-scroll? What are some common errors or extra st ...

Why doesn't express.js throw an error when the variable 'app' is used within its own definition?

When working with express.js, I find it puzzling that createApplication() does not throw an error. This is because it uses app.handle(...) within an anonymous function that defines the same variable 'app'. I attempted to replicate this in jsFidd ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

Is employing absolute paths in our confidential Node dependencies a good idea?

I have recently organized our codebase's React components into a separate dependency to make them reusable across different projects. To improve readability, all components now utilize Webpack aliases: import TestComponent from 'components/TestCo ...

Drag the label into the designated paragraph to copy the text. Click on the specific point to transfer the text

How can I copy the text from a label to a specific point by dragging it? <label id="text_to_be_copied" > i am a student </label> Below is a paragraph where I want to paste the copied text: <p> this is the content where I want to copy t ...

Saving JSON data as a file on server

Currently, I am running a localhost website on my Raspberry Pi using Apache and I am seeking advice on how to export a JSON string to a file on the Raspberry Pi itself. While I do know how to export a file, I am unsure of how to send it to the Raspberry Pi ...

Angular component receives only initial value from BehaviorSubject

I am facing an unusual issue where I have created a service to emit the value of the item clicked on the navbar in order to trigger a modal. import { EventEmitter, Injectable } from "@angular/core"; import { BehaviorSubject, Subject } from " ...

Angular form group not providing data upon submission

Encountering a peculiar issue here. When the submit button is clicked, my angular form group does not return anything. Additionally, nothing is being logged to the console upon clicking. Interestingly, this form is almost identical to another one that func ...

Update the mat-chip-remove positioning attributes

While browsing through the mat-chip documentation, I came across the following information: MatChipRemove Provides proper (click) support and styling for using the Material Design "cancel" icon, which can be found at https://material.io/icons/#ic_cancel. ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Is it possible to use a hash map to monitor progress while looping through this array in JavaScript?

I've been exploring some algorithmic problems and I'm puzzled about the most efficient way to solve this particular question. While nested for loops are an option, they don't seem like the optimal choice. I'm considering using a hash ma ...

Aurelia: Understanding the Integration of a View/ViewModel from an npm Package

We've decided to implement Aurelia for the frontend of our application. With multiple projects in the pipeline, we are looking to streamline the process by packaging our custom code into npm packages that can be easily integrated by developers. This w ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...