Snk
Snk

Reputation: 149

TypeError: Cannot read property 'length' of undefined in Angular app

I'm creating a quiz app for practice and needs to display one MCQ at a time. Coded the following but facing an error as said in title.

By googling other similar questions on Stack Overflow,I did try their solutions: Tried console logging, if there was any file missing from Node_Modules/typescript but everything was perfect. Also tried to update Node_Modules and CLI to latest version, but no luck.

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');
      }   
}

I'm really not getting what is being missed!

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>

Upvotes: 0

Views: 399

Answers (1)

tlt
tlt

Reputation: 15211

your array iteration happens before you get any data from observable. try modifying your code to something like this:

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

Upvotes: 1

Related Questions