showcasing products from database with the help of Angular 12

Here are the files related to the item:

Item file

And here is the component file:

Component file

Lastly, this is the data service file:

Data Service file

However, issues arise when testing the code with console log statements as it indicates that the data from the service is undefined.

import { Component, OnInit } from '@angular/core';
import { Item } from '../item';
import { DataService } from '../data.service';

@Component({
  selector: 'app-shopping-item',
  templateUrl: './shopping-item.component.html',
  styleUrls: ['./shopping-item.component.css'],
  providers: [DataService]

})
export class ShoppingItemComponent implements OnInit {
  shoppingItemList: Item[] = [];
  
  constructor(private dataservice: DataService){}

  getItems(){
    this.dataservice.getShoppingItems()
    .subscribe(items =>{
      this.shoppingItemList.push(items),
      console.log('data from dataservice '+ this.shoppingItemList[0].itemName);
    })
  }
  addItem(form: any){

    console.log(form)
  }

  ngOnInit(): void {
    this.getItems();

  }
}

Answer №1

When dealing with an array retrieved from an API call, you have two options: either assign it directly to the property or destructure the array into the property.

It appears that you might be inadvertently pushing an array inside another array, which could result in undefined errors!

import { Component, OnInit } from '@angular/core';
import { Item } from '../item';
import { DataService } from '../data.service';

@Component({
  selector: 'app-shopping-item',
  templateUrl: './shopping-item.component.html',
  styleUrls: ['./shopping-item.component.css'],
  providers: [DataService]
})
export class ShoppingItemComponent implements OnInit {
  shoppingItemList: Item[] = [];
  
  constructor(private dataservice: DataService){}

  getItems(){
    this.dataservice.getShoppingItems()
    .subscribe(items =>{
      this.shoppingItemList = items; // approach 1
      // this.shoppingItemList.push(...items); // approach 2
      console.log('data from dataservice '+ this.shoppingItemList[0].itemName);
    })
  }
  addItem(form: any){
    console.log(form)
  }

  ngOnInit(): void {
    this.getItems();
  }
}

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 appropriate typescript type for an array payload when using the fetch API?

My current method involves using fetch to send URL encoded form data: private purchase = async () => { const { token } = await this.state.instance.requestPaymentMethod(); const formData = []; formData.push(`${encodeURIComponent("paymentTok ...

Looking to organize, refine, and establish a default value with the help of rxjs

In my Angular application, I have an observable that is linked to a reactive forms dropdown control. My goal is to filter, sort, and display the default value. I've created two separate implementations - one for filtering and sorting without displayin ...

Differences between encoding URL variables in HREF and using JS window.location for onclick events

For some reason, this particular hyperlink is not functioning properly. I have a Javascript redirect (window.opener.location) where I pass several variables through the URL. The problem arises when these variables contain apostrophes. In PHP, I am using UR ...

What is the process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

Update the second dropdown list based on the selection made in the first dropdown list in Vue.js

My goal is to dynamically change the options in the second select list based on the value selected in the first one. I initially achieved this by creating two separate Vue instances for each select, but I wanted a more streamlined approach for a cleaner ap ...

Ways to create a table with columns from various fields obtained through an API call

Looking to preprocess data received from an API, the raw data is structured as follows: Desiring to dynamically generate a table with columns based on the fields task_name and saved_answers. It's important to note that saved_answers might contain var ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

The Nrwl Nx administrative page located within the server instance

Hopefully my question is clear. We are working with a monorepo at nrwl that includes 2 applications, client and client-admin. I'm looking for the best way to deploy both of these applications on the same server but with different routes. Client-app ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

Troubles with Custom Control Component: ControlValueAccessor and Validator Out of Sync with Form Group

Background: My custom email control component, EmailControlComponent, is designed to implement both ControlValueAccessor and Validator. The validate() method of this component takes a single parameter of type AbstractControl. As specified in Angular' ...

exploring numerous boxes in an engaging and educational tutorial

Explaining this in the title was a bit tricky, but what I want to create is an interactive tutorial. In this tutorial, the user will click on an area or product they want to clean or use for cleaning. After clicking, another box with relevant information w ...

Setting up of imagemagick node module using linuxbrew

Having trouble installing imagemagick-native as it's showing an error. Tried using the following command to install: npm install imagemaick-native --save > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c45414d ...

Rails Ajax form submission not working

I recently set up a basic Google form on my website and used this website to extract the HTML code for display. However, upon hitting submit, nothing happens - the page seems to be frozen. I'm attempting to redirect the form submission to another page ...

Having trouble running Ajax with JavaScript on a Wamp server

Exploring the realm of ajax, I embarked on a journey guided by a YouTube tutorial to construct a basic food search application. The concept was simple - users would input the name of a food item, and if available, its name would be displayed below. On the ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

Searching for values using keys in Angular

Currently, I am working on a project using Angular where I need to store information based on specific identifiers. To display this information in the Angular application, I am pulling data for different identifiers and showing it on the screen. At the mo ...

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

Adding a combination of HTML and Javascript to an element can result in unexpected behavior

http://jsfiddle.net/PeKdr/ Encountering an issue when having a JavaScript variable that contains both HTML and JavaScript, resulting in unexpected behavior in the output window. Neither of the buttons - one triggering the function appendTheString() or the ...

Attempting to extract text by utilizing the getText() function in Selenium along with Javascript

Attempting to use the getText() method in Selenium and Javascript, but encountering issues. const {Builder, By, Key, until} = require('selenium-webdriver'); (async function example() { let driver = await new Builder().forBrowser('chrom ...