0

I have following interface:

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

And following component:

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

Result of console.warn

But when i try to get values of ClosestLocation using any function, for example:

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

I get error in console:

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)

How can I assign value to ClosestLocation so that I can access it later? When I changed API call to return object type of

ClosestLocation:IQuest[]|any;

I'm getting the same problem.

5
  • When you are calling the method "displayQuestion"? Ideally it should be inside of your subscription. Commented Jan 15, 2023 at 14:49
  • I called it after getClosestQuest(), but if i call it inside subscription I'm getting "range: undefined" Commented Jan 15, 2023 at 16:16
  • Looks like you have the wrong casing. JavaScript is case sensitive Commented Jan 15, 2023 at 16:44
  • Where @AluanHaddad? Commented Jan 15, 2023 at 16:49
  • In your console log, showing the object structure, the property names are lowercase. However, you may have other problems as well I haven't looked too closely. Commented Jan 15, 2023 at 16:52

1 Answer 1

0

Try this

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

This also could be due to ClosestLocation being undefined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.