Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度获取数组类型错误:无法读取未定义的属性“1”_Angular - Fatal编程技术网

Angular 角度获取数组类型错误:无法读取未定义的属性“1”

Angular 角度获取数组类型错误:无法读取未定义的属性“1”,angular,Angular,我有以下JSON结构: { "daypart": [ { "temperature": [ 45, 27, 47 ] } ] } 我试图显示上面JSON API中的数组。我只想显示这个数组的第一个元素,但是我得到了以下错误 Error: Uncaught (in promise): TypeError: Cannot read property '1' of undefined 代码: this

我有以下JSON结构:

{
  "daypart": [
    {
      "temperature": [
        45,
        27,
        47
      ]
    }
  ]
}
我试图显示上面JSON API中的数组。我只想显示这个数组的第一个元素,但是我得到了以下错误

Error: Uncaught (in promise): TypeError: Cannot read property '1' of undefined
代码:

 this.http.get("xxxxxxxx")
      .subscribe(data => {

        let f = data["daypart"][0]

        this.duhok = f

        console.log("duhok" +  this.duhok["temperature"][1])

      })
Html:

    {{duhok.temperature[1]}}°

我在这里大胆猜测,html是在请求得到解决之前呈现的。 尝试在ngIf块中包装插值

<div *ngIf="duhok">
 {{duhok.temperature[1]}}°
</div>

我在这里大胆猜测,html是在请求得到解决之前呈现的。 尝试在ngIf块中包装插值

<div *ngIf="duhok">
 {{duhok.temperature[1]}}°
</div>

可能是因为当您到达该组件时,数据没有解析。您可以将解析器添加到该路由上的该组件,以确保在到达该组件时数据已被重新解析。选中此项:
可能是因为到达该组件时数据未解析。确保已在该路由上添加数据,以便在该路由上重新解析。选中此项:

如果只想显示整个JSON结构中的第一个温度,可以使用以下代码。使用异步管道的优点是,您不必手动订阅/取消订阅可观察的内容

TS:

HTML:


如果只想显示整个JSON结构中的第一个温度,可以使用以下代码。使用异步管道的优点是,您不必手动订阅/取消订阅可观察的内容

TS:

HTML:


错误是不言自明的,您的温度变量未定义。当数据输入时,请尝试执行一些控制台日志,以查看错误的位置。第一个元素是['temperature'][0]错误是不言自明的,您的温度变量未定义。当数据传入时,请尝试执行一些控制台日志,以查看您的错误所在。第一个元素是['temperature'][0]
{{(getData() | async)?.daypart[0].temperature[1]}}