[英]displaying items from DB using Angular 12
項目文件
組件文件
數據服務文件
當我使用控制台日志語句測試我的代碼時,它說來自服務的數據未定義
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(); } }
如果您從 API 調用接收到一個數組,那么您需要將其直接分配給屬性 (1) 或將數組解構為屬性 (2)
目前我猜你正在將一個數組推入一個數組,這可能會導致未定義的錯誤!
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.