首页 > 解决方案 > 恢复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")
}

}

标签: jsonangularhttprequest

解决方案


从 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]
  });
}

我没有看到这里有任何损失可以恢复。


推荐阅读