我有一个像这样的json:
[ {
"id": 1,
"libraryName": "lib1",
"bookName": "book1",
"bookPrice": 250.45,
"unitSold": 305
},
{
"id": 2,
"libraryName": "lib1",
"bookName": "book2",
"bookPrice": 450.45,
"unitSold": 150
},
{
"id": 3,
"libraryName": "lib1",
"bookName": "book3",
"bookPrice": 120.25,
"unitSold": 400
}]
我想在列表中恢复此json的所有bookName,而无需创建getBookNames方法(因为我想要json的任何字段的标准方法)因此,在component.ts中,我使用了:
sales:any;
getSale () {
this.service.getSales().subscribe(data=> {this.sales = data,
console.log(this.sales.bookName)
})
}
它在控制台中给了我未定义的对象!如何解决此问题而不创建方法getBookNames()?
这是我的班级:
export interface Sale {
id: number
bookname : string
Libraryname: string
Bookprice : number
Unitsold : number
}
这是我的服务:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Sale } from './Sale';
@Injectable({
providedIn: 'root'
})
export class MyserviceService {
constructor(private http: HttpClient) { }
getSales () {
return this.http.get<Sale>("http://localhost:8081/sales/all")
}
}
在这种情况下,休养意味着什么?
从API获得的数据是一个数组。因此,您可以使用数组map()
函数从元素获取所有属性的列表。尝试以下操作
sales:any;
getSale () {
this.service.getSales().subscribe(data=> {
this.sales = data,
console.log(data.map(item => item.bookName); // <-- output: ['book1', 'book2', 'book3'];
});
}