【问题标题】:Retrieve data from JSON file by ID in Angular. TypeError: items.find is not a function在 Angular 中按 ID 从 JSON 文件中检索数据。 TypeError: items.find 不是函数
【发布时间】:2020-06-24 18:56:06
【问题描述】:

试图通过 id 从 JSON 文件中获取数据,但在控制台中出现错误

 TypeError: items.find is not a function

{
"product" :{
       "data" : [
           { "itemID" : "1" , "name" : "pen" , "qty" : "8" }`,
           { "itemID" : "2" , "name" : "notepad" , "qty" : "5" } 
  ]

} }

我正在使用的函数 where TypeError: items.find is not a function in console

       getitems(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;

         });
         })
          );
         }
          office.ts
            export class officeitems {
               itemID: string;
               name: string;
               qty: string;

            }

【问题讨论】:

  • 试试map(res: any) =&gt; res.product.data.find((item: Fruits) =&gt;item.itemID=== itemID)
  • 非常感谢,它成功了。

标签: json angular nested find typeerror


【解决方案1】:

您需要正确使用您的结构。您的结构是一个对象,您将其视为一个数组。

因此,您需要从产品属性中获取数据,因为数据是您的数组。

您需要更改您的 getItems 方法并修复定义的接口。

   map((product: any) => { // <- you need to use your interface Product { } instead of any 
    return product.data.find((item: Fruits) => {
      return item.itemID=== itemID;
    });

{
  "product" :{
       "data" : [
           { "itemID" : "1" , "name" : "pen" , "qty" : "8" }`,
           { "itemID" : "2" , "name" : "notepad" , "qty" : "5" } 
    ]
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多