TypeError:无法读取属性' length'在Angular应用程序中未定义

时间:2018-04-21 07:04:44

标签: angular

我正在为练习创建一个测验应用,并且需要一次显示一个MCQ。 编码如下,但面临标题中所述的错误。

通过在Stack Overflow上搜索其他类似的问题,我确实尝试了他们的解决方案:尝试控制台日志记录,如果Node_Modules / typescript中缺少任何文件,但一切都很完美。还试图将Node_Modules和CLI更新到最新版本,但没有运气。

Quiz.component.ts:

export class QuizComponent implements OnInit {
  radio1: string;
  value: string;
  target: any;
  quizName = 'QUIZ APPLICATION';
  counter=0;
questArray: any[];
questArray1:any[];
questArray2: any[];

  constructor(private newService: MyDataService) //service define
   { }
  ngOnInit() { 
    this.newService.fetchData()
    .subscribe(response => this.questArray = response.json());
  `   `
  this.callingArray();  

  }

    callingArray() {

    for(var i=0;i<=this.questArray.length;i++)
    {
        this.questArray1=this.questArray[i];
        this.questArray2=this.questArray[i+1];   
    }
     }

Service.ts:

export class MyDataService {
  constructor(private http: Http) 
  {}
  fetchData()
      {
        return this.http
        .get('../assets/questions.json');
      }   
}

我真的没有得到错过的东西!

JSON:

[  
  {
    "QUES":"The Government of India (GoI) has launched the web-based application e-FRRO scheme for foreigners. What does ‘FRRO’ stands for ?",
    "OP":[ "Foreigners Regional Registration Office", "Foreigners Registry Registration Office", "Foreigners Reacceptance Registration Office", "Foreigners Regaining Registration Office" ]
},

  {

        "QUES": "H",
        "OP":["ADASD" , "ASDAD", "ASDASD", "ASDADS"]

    }

]

HTML:

<div *ngFor="let abc of questArray1;let j = index" >

           {{j+1}}.{{abc.QUES}}

        <br>
      <input type="radio" name="s">{{abc.OP[j]}}

      <br>
      <input type="radio" name="s">{{abc.OP[j]}}

      <br>
      <input type="radio" name="s">{{abc.OP[j]}}

      <br>
      <input type="radio" name="s">{{abc.OP[j]}}

      <br>

        </div>

1 个答案:

答案 0 :(得分:1)

在从observable获取任何数据之前,您的数组迭代会发生。尝试将代码修改为以下内容:

this.newService.fetchData().subscribe(response => {
   this.questArray = response.json();
   this.callingArray();
});