JSON数据到特定类型的数组[Angular]

时间:2019-02-18 21:55:05

标签: javascript angular typescript

我正在尝试将JSON数据转换为Recipe []。

这是API的响应:

{
    "criteria": {
        "requirePictures": true,
        "q": null,
        "allowedIngredient": null,
        "excludedIngredient": null
    },
    "matches": [
        {
            "imageUrlsBySize": {
                "90": "https://lh3.googleusercontent.com/8H_kR4fF6IE517FKDHGOyVHEgNmmCdhX_Yz2YfxIDJgCQoU_NJ-hw_FJ1jEolQPPAfoKuKMw4jYjJK512gTyfQ=s90-c"
            },
            "sourceDisplayName": "Mrs. Happy Homemaker",
            "ingredients": [
                "frozen meatballs",
                "pasta sauce",
                "shredded mozzarella cheese",
                "shredded parmesan cheese",
                "Italian seasoning"
            ],
            "id": "Meatball-Parmesan-Casserole-2626493",
            "smallImageUrls": [
                "https://lh3.googleusercontent.com/3dbNmfS4BI-7CUsm2WYE8l7-90CNi3rQPUkO5EMc0gts_MBUAVZlTngm-9VHshp9toXl73RKwiUs9JQCpx6RoQ=s90"
            ],
            "recipeName": "Meatball Parmesan Casserole",
            "totalTimeInSeconds": 900,
            "attributes": {
                "course": [
                    "Main Dishes"
                ]
            },
            "flavors": null,
            "rating": 4
        }
    ],
    "facetCounts": {},
    "totalMatchCount": 1228808,
    "attribution": {
        "html": "Recipe search powered by <a href='http://www.yummly.co/recipes'><img alt='Yummly' src='https://static.yummly.co/api-logo.png'/></a>",
        "url": "http://www.yummly.co/recipes/",
        "text": "Recipe search powered by Yummly",
        "logo": "https://static.yummly.co/api-logo.png"
    }
}

这是我尝试使用地图运算符解决的方法。

  list(): Observable<Recipe[]> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

但是它说“对象类型上不存在匹配项”。我想念什么吗?如何访问“匹配”数组,以便为​​数组创建Recipe实例?我该使用地图运算符还是以其他方式使用?

2 个答案:

答案 0 :(得分:0)

  list(): Observable<any> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

list(): Observable<Recipe> {
    return this.http.get('url').pipe(
      map(data =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

尝试执行其中一项操作,因为您将从url中获取一个json对象,并且在可观察对象中,您正在提供对象数组。

答案 1 :(得分:0)

所以我通过将其替换为:

  list(): Observable<Recipe[]> {
    return this.http.get('url').pipe(
      map((data: any) =>
        data.matches.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

数据->(数据:任意)