Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.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
Javascript 角度类型错误:无法读取属性';颜色';试图读取数据的未定义错误_Javascript_Json_Angular - Fatal编程技术网

Javascript 角度类型错误:无法读取属性';颜色';试图读取数据的未定义错误

Javascript 角度类型错误:无法读取属性';颜色';试图读取数据的未定义错误,javascript,json,angular,Javascript,Json,Angular,我试图从Angular 4中本地存储的文件中读取一些数据 以下是相同的数据: { "color": "blue" } 下面是component.ts文件中的代码: import { Component, OnInit } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'app-home', templateUrl: './home.component

我试图从Angular 4中本地存储的文件中读取一些数据

以下是相同的数据:

  {
    "color": "blue"
  }
下面是component.ts文件中的代码:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class DashboardComponent implements OnInit {

  data;

  constructor(private http: Http) {
    this.http.get('../../assets/data.json')
      .subscribe(res => this.data = res.json());

    console.log(this.data.color);
  }

  ngOnInit() {
  }

}
我不断地发现这个错误:

错误:未捕获(承诺中):TypeError:无法读取未定义的属性“color”


我做错了什么/我如何修复它?

将console.log放在订阅中

this.http.get('../../assets/data.json')
  .subscribe(res => {
     this.data = res.json();
     console.log(this.data.color);
  }
)

获取错误:component.ts(15,47):“)”应为..订阅(res=>{this.data=res.json();console.log(this.data.color);});您正在通过订阅获取具有“颜色”属性的数据。调用构造函数时,数据仍然未定义。因此,如何将数据放入数据变量中?这可能会有帮助:)不,仍然未定义。您在哪里检查它?与console.log()位于同一位置?还是在视野中?您是否更改了ngOnInit?