首页 > 解决方案 > 从Angular中的Json文件中按特定字段获取数据

问题描述

JSON文件具有以下结构

localjson.json
  {
    "Product" :{
           "data" : [
               { "itemID" : "1" , "name" : "Apple" , "qty" : "3" }`,
               { "itemID" : "2" , "name" : "Banana" , "qty" : "10" } 
      ]

    } }

所以通过 id 获取项目,我拥有的是

       getfruits(itemID: string) {
        return this.http.get<Array<Fruits>>('assets/localjson.json')
            .pipe(
               map((items: Array<any>) => {
              return items.find((item: Fruits) => {
               return item.itemID=== itemID;

             });
           })
              );
             }

水果.ts

    export class Fruits{
          itemID: string;
            name: string;
            qty: string;

     }

它说 TypeError: items.find is not a function

标签: jsonangulartypescriptservice

解决方案


试试这样

export interface Fruits {
  itemID: string;
  name: string;
  qty: string;
}

getfruits(itemID: string) {
 return this.http.get<Array<Fruits>>('assets/localjson.json').pipe(
  map((items: { Product: { item: Fruits[] } }) => {
    return items.Product[0].find((item: Fruits) => {
      return item.itemID === itemID;
    });
  })
);

}


推荐阅读