Home > Enterprise >  displaying items from DB using Angular 12
displaying items from DB using Angular 12

Time:12-09

the Item file

enter image description here

component file

enter image description here

the data service file

enter image description here

when I test my code with console log statements it says data from 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();

  }
}

CodePudding user response:

If you are receiving an array from the API call, then you need to either assign it directly to the property (1) or destructure the array into the property (2)

Currently I guess you are pushing an array inside an array, which might lead to undefined error!

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; // solution 1
      // this.shoppingItemList.push(...items); // solution 2
      console.log('data from dataservice '  this.shoppingItemList[0].itemName);
    })
  }
  addItem(form: any){

    console.log(form)
  }

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

  }
}
  • Related