Angular无法读取未定义

时间:2017-06-08 20:17:35

标签: json angular typescript

我遇到了从json文件调用数据的问题。当我单击一个按钮使其出现在textarea中时,它对第一次单击没有任何作用,但在此之后工作就像预期的那样。该程序所做的是从仪表板获取一个id,并根据该ID获取不同的json文件。 该程序显示错误:

错误类型错误:无法读取未定义的属性“数据”     在StepService.webpackJsonp.102.StepService.populateList(step.service.ts:69)     在CalibrationDetailComponent.webpackJsonp.101.CalibrationDetailComponent.next

step.service.ts

private jsonData: any; //Json data
public list: String[] = []; //Holds the list of steps
public listLength: number; //Length of the list
public listCurrent: number = 0; //Current step the list is on

//Gets the json file
  public getJson(): Observable<any> {
    return this.http.get(this.jsonUrl)
      .map(response => response.json());
  }

  //Subscribe
  public subScribe2Json() {
    this.getJson().subscribe(data => (this.jsonData = data));
  }

  //Populates the list from the json so I can pull out specific steps
  public populateList() {
    this.jsonData.data.forEach(element => { //The line that throws the error
      this.list.push(element.name);
    });
    this.listLength = this.list.length;
  }

  //Returns the mainStepText with the current step
  public getJsonData(): String {
    this.mainStepText = this.list[this.listCurrent];
    return this.mainStepText;
  }

校准detail.component.ts

下一步按钮方法

next() { //Advances step
    this.stepService.subScribe2Json();
    if (this.stepService.listCurrent < 1) { //Makes sure only runs once to populate the list
      this.stepService.populateList(); //Populates list from the json array
     }
    if (this.stepService.listCurrent < this.stepService.listLength) { //make sure dont go past number of steps
        this.stepService.subScribe2Json(); //Sub to list
        this.mainStepText = this.stepService.getJsonData(); //Grab the data from the list and output to main textarea
        this.stepService.listCurrent ++; //Increments the step

1 个答案:

答案 0 :(得分:1)

这不是一个完整的解决方案,而是解决问题的答案。并根据您想要达到的目标,将您的思想指向正确的方向。

你打电话

this.stepService.subScribe2Json();
if (this.stepService.listCurrent < 1) {
...

这会调用第一种方法,而不是等待数据就立即调用第二种方法。当然它失败了,因为它还没有。

根据您的使用案例,您可以返回Observable(可能将其更改为Promise,...不是100%确定)然后:

return this.getJson().subscribe(data => (this.jsonData = data));

等等

this.stepService.subScribe2Json().then(/* do all stuff here */);

或初始化

private jsonData: any = [];

但当然你在第一次跑步时没有任何东西。