Angular TypeScript无法读取未定义错误的属性

qyswt5oh  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(214)

我有以下界面:

export interface IQuest {
Id: number,
lat: number,
lon: number,
Question:string,
Answer:boolean,
IsDone:boolean,
Correct:boolean,
Range:number}

以及以下组件:

export class AppComponent implements OnInit{

currentUserLatitude=49.8121157;
currentUserLongitude=19.041796;
constructor(private http:HttpClient){};

data:IQuest[]|any=[];

ClosestLocation:IQuest|any;

ngOnInit(){
this.getClosestQuest();
}

getClosestQuest(){   
let url = "http://127.0.0.1:5153/api/GetClosest? 
cuLon="+this.currentUserLongitude+"&cuLat="+this.currentUserLatitude;
console.log("getClosestQuest() -nowWorking");
this.http.get(url).subscribe(data=>{
  console.warn(data);
  console.log(data);
  
  this.ClosestLocation=data;
});

但是当我尝试使用任何函数获取ClosestLocation的值时,例如:

displayQuestion(){
console.warn("range: "+this.ClosestLocation.Range);
}

我在控制台中收到错误:

ERROR TypeError: Cannot read properties of undefined (reading 'Range')
at AppComponent.displayQuestion (app.component.ts:81:61)
at AppComponent.ngAfterViewInit (app.component.ts:31:10)
at callHook (core.mjs:2488:22)
at callHooks (core.mjs:2457:17)
at executeInitAndCheckHooks (core.mjs:2408:9)
at refreshView (core.mjs:10490:21)
at detectChangesInternal (core.mjs:11624:9)
at RootViewRef.detectChanges (core.mjs:12115:9)
at ApplicationRef.tick (core.mjs:25402:22)
at ApplicationRef._loadComponent (core.mjs:25440:14)

如何给ClosestLocation赋值,以便以后访问它?当我更改API调用以返回对象类型

ClosestLocation:IQuest[]|any;

我也有同样的问题。

k4emjkb1

k4emjkb11#

试试这个

console.warn("range: "+this.ClosestLocation?.range);

这也可能是因为ClosestLocationundefined

相关问题