【问题标题】:Angular TypeScript cannot read properties of undefined errorAngular TypeScript 无法读取未定义错误的属性
【发布时间】:2023-01-15 22:42:36
【问题描述】:

我有以下界面:

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;

我遇到了同样的问题。

【问题讨论】:

    标签: angular typescript properties undefined


    【解决方案1】:

    尝试这个

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

    这也可能是由于 ClosestLocation 变成了 undefined

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2017-06-26
      • 1970-01-01
      • 2018-06-04
      • 2018-07-01
      • 2019-02-02
      • 2022-01-22
      相关资源
      最近更新 更多