json - 恢复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
}]
我想在列表中恢复这个 json 的所有 bookNames 而不创建方法 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;
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]
});
}
我没有看到这里有任何损失可以恢复。
推荐阅读
- android - 使用 Fragment 和 Activity 执行生命周期流程的问题
- bash - 如何使用 shell 命令在匹配行之后获取一些行
- reactjs - 用于非 SPA 的 Laravel Sanctum API 令牌
- python - “NoneType”对象没有属性“运行”张量流
- javascript - 使用 Fabric js 调整高清图像大小
- python - 使用 for 循环删除数据帧行
- attributes - header.php wordpress 中隐藏的混合内容
- powershell - 如何使用 powershell 和 Orchestrator 2016 连接到 microsoftTeams?
- node.js - 使用 mongoose 将对象附加到 mongoDB 中的对象数组
- visual-studio-code - 自动完成插件 Visual Studio Code 以灰色插入字符串