恢复json的字段



我有一个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
}]

我想在不创建方法getBookNames的情况下恢复列表中这个json的所有bookNames(因为我想要json的任何字段的标准方式(所以,在我使用的组件.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;
unitsSold = [];
getSale () {
this.service.getSales().subscribe(data=> {
this.sales = data,
console.log(data.map(item => item.bookName)); // <-- output: ['book1', 'book2', 'book3'];
console.log(data.map(item => item.id)); // <-- output: [1, 2, 3];
this.unitsSold = data.map(item => item.unitSold); // <-- [305, 150, 400]
});
}

我看不出这里有什么东西可以用来疗养。

最新更新