Home > Mobile >  Angular can't access properties of variables in typescript
Angular can't access properties of variables in typescript

Time:01-16

I have following code:

data:IQuest[]|any=[];

ngOnInit(){
this.getData();
console.log(this.data[1].Question);
}

getData(){     
  let url = "http://127.0.0.1:5153/Quests";
  this.http.get(url).subscribe(data=>{
  this.data=data;     
});
}

export interface IQuest {
Id: number,
lat: number,
lon: number,
Question:string,
}

I can't access values inside data property in typescript, for example when I call console.log, like in code above I'm getting error like this:

ERROR TypeError: Cannot read properties of undefined (reading 'Question')
at AppComponent.ngOnInit (app.component.ts:32:30)

On the other hand when I want to display values in html, they display properly and there is no problem with access, example:

<div *ngFor="let element of data">
  {{element.question}}
</div>

Which lists value of propertie one under another. So why can't I access those values in TypeScript?

CodePudding user response:

Could try removing the |any on the data definition. Or casting it when you populate it like this.data=data as IQuest[];

CodePudding user response:

You have a couple issues in your code, some have already been mentioned by others.

  1. this.data[1] is accessing the second element in the array which might be different from your html (in case you only return 1 item).
  2. your html is accessing question (lowercase q) while your typescript is accessing Question (uppercase Q).
  3. as mentioned by @Fussel, you are loading your data asynchronously meaning that by the time you do the console.log, the this.data = data may not have been executed yet. Move the console.log directly below this.data = data inside the subscription.

Looking at the other question you've posted (Angular TypeScript cannot read properties of undefined error). Number 3 is probably the cause of this error and when that is fixed number 2 will probably be your next error :). As the debugger shows that you actually return an object with the question (lowercase q) variable. that also means that your IQuest definition is wrong (same goes for the Id property (uppercase I)).

Some other things to watch out for are: saying that this.data is an IQuest[] does not mean it actually is. if your return something else from the HttpClient then javascript will happly put it in that variable.

Also as mentioned by @Nando IQuest[]|any means that the variable is an IQuest[] or might be anything else. This will not fix your issues as this is something used compilte time by typescript and your error is generated in runtime by javascript but it would be better to change it and just remove the |any part.

  • Related