【问题标题】:Parsing array inside a JSON response在 JSON 响应中解析数组
【发布时间】:2021-08-15 01:20:06
【问题描述】:

所以我正在研究 REST API,它以 Angular 的形式使用并以以下格式获取响应

我得到了简短的描述,但是当我尝试使用 *ngfor 显示它不起作用时,我是 Angular 的绝对初学者,所以任何指导都会有所帮助,谢谢

{
    "data": {
        "Query": "sample query",
        "numbers": [
            "0013290",
            "160011736",
            "130004057",
            "2075333",
            "0015416"
        ],
        "Scores": [
            94.66,
            94.48,
            78.12,
            0.17,
            0.15
        ],
        "Short_descriptions": [
            "sample 1",
            "sample 1",
            "sample 1",
            "sample 1",
            "sample 1"
        ],
       
    }
}


 this.query='{ "query": "sample query" }';
    this.homeService.getTop5KbArticles(this.query).subscribe(data => {
    this.KBdata =data["data"];
     this.shortDesc =this.KBdata["Short_descriptions"]

<div class="col-md-5" *ngFor="let x of shortDesc">
<p>{{x.Short_descriptions}}</p>
</div>

```

【问题讨论】:

  • {{x.Short_descriptions}}

    更改为

    {{x}}

  • 如果我正确理解了您的问题,您想要向后兼容吗? JSON.stringify,所以像这样 var myJsonString = JSON.stringify(yourArray);
  • @Nonik 谢谢你的工作
  • 对不起,我说我是一个绝对的初学者,让我改写一下,如果我想在 ngfor 中使用其他字段,如分数和数字,并带有简短的描述
  • 那么你的数据是错误的。似乎您的数据是一组数组,您首先需要将数据映射为正确的格式,然后将其传递给您的视图,似乎您需要这样的东西 [{Short_description:"sample 1", Score:94.66, number:"0013290" }]

标签: json angularjs angular


【解决方案1】:

{{x.Short_descriptions}} 替换为{{x}}

当你写*ngFor="let x of shortDesc"时,这意味着x将是shortDesc的一个项目,它是一个简单的字符串数组。

【讨论】:

  • 明白了,如果我想在 ngfor 中使用分数和数字等其他字段和简短描述该怎么办
  • 您可以更改您的ngFor 以公开索引ngFor="let x of shortDesc, let index as I" 并像KBData.scores[i] 一样重用i。或者改变你的数据结构来创建一个对象数组。
  • 当我这样做时出现以下错误无法绑定到“ngForAs”,因为它不是“div”的已知属性。
  • 在我之前的评论中有一个小错字:ngFor="let x of shortDesc; index as i"
猜你喜欢
  • 2011-05-20
  • 2021-11-13
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 2017-09-23
  • 2020-09-06
相关资源
最近更新 更多