Error in Angular TypeScript occurs when attempting to read properties of an undefined value

Here is the interface that I am working with:

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

Along with the 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;
});

https://i.sstatic.net/ld6ep.png

However, I encounter an error when attempting to access values of ClosestLocation using a function like this:

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

The error message in the console reads:

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)

I'm looking for a way to assign a value to ClosestLocation so that I can access it later without encountering errors. I have tried changing the API call to return object type of

ClosestLocation:IQuest[]|any;

But the issue persists.

Answer №1

Give this a shot

console.log("distance: "+this.NearestSpot?.distance);

Another possibility is that NearestSpot is not defined.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a specific type of keys, attempting to set two instances of those keys simultaneously will result in an error of that type

Consider this scenario: type Example = { x: string, y: number } const a: Example = { x: "x", y: 1 } const b: Example = { x: "y", y: 2 } const issue = (keys: (keyof Example)[]) => { keys.forEach(key => { a[key] ...

Issue with TypeScript not recognizing node_modules symlink in Docker container

I'm currently working on containerizing an Express app in TypeScript. However, I am facing issues linking node_modules that have been installed outside the container. Even though a volume is mounted for development, I keep encountering errors in my ed ...

Cypress: Uncovering the method invoked by a button click

I'm currently utilizing Vue3 with Vite and Cypress. My Vue3 component utilizes the script setup SFC syntax. Below is the code snippet for my component: <template> <div> <button data-cy="testBtn" @click="btnClick()&q ...

Make sure to always target a specific DIV element, regardless of whether any of its child divs are

I have a div named "box" nested inside another div called "container." When I click on the box, I am able to retrieve its ID perfectly. However, when I click on the container, I want to obtain the ID of the box instead of the container. Is there a way fo ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

I am experiencing an issue where the Javascript keydown event does not recognize the character "@" in the EDGE browser

Currently, I am developing a mentioning directive that displays a list of users when the user types in an input field (a div with contentEditable=true). The user can then insert the name of the desired user in a specific format. The list is supposed to be ...

Transform the object into an array of JSON with specified keys

Here is a sample object: { labels: ["city A", "city B"], data: ["Abc", "Bcd"] }; I am looking to transform the above object into an array of JSON like this: [ { labels: "city A", data: "Abc" }, { labels: "city B", data: "Bcd" }, ]; ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Allow TypeScript function parameters to accept multiple elements from an enumeration

Enumerating my options. export enum Selection { CHOICE_ONE = 'one', CHOICE_TWO = 'two', CHOICE_THREE = 'three', CHOICE_FOUR = 'four', } I am looking to design a function that accepts an array, but re ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...

Dynamic form groups in Angular: Avoiding the issue of form inputs not binding to form groups

Purpose My goal is to develop a dynamic form in Angular that adjusts its fields based on an array received from the backend. For example, if the array contains ["one", "two", "three", "four"], the form should only ...

Can we specify the type of a destructured prop when passing it as an argument?

I have implemented Material UI's FixedSizeList which requires rendering rows in the renderRow function and passing it as a child to the component. The renderRow function accepts (index, style, data, scrolling) as arguments from the FixedSizeList comp ...

Instructions for activating the routerLink feature within a mat-tab

I recently implemented lazy loading for a feature module in my Angular app by configuring the routing in Routing.module.ts from app-routing.module.ts. The default route in the featured routing module loads the LccpTrackerComponent, which contains 3 child r ...

Looking to display cities based on the country chosen in Angular?

Hi everyone! I need help with creating a cascade type dropdown for displaying cities based on the selected country. I have a list of about 3,000 cities, but I only want to show the cities from the chosen country. Here is the structure of the country: " ...

Organizing a store in a hierarchical structure

I am currently facing an issue with creating a hierarchical store in Angular. My goal is to have multiple reducers that work on specific parts of the application. Here's the scenario: I am working on an HR application that has a talent (employee) mod ...

Angular2 - Anticipating the arrival of data from an observable

When working with Angular2 templates, it seems like they handle waiting for a list to return from an observable just fine. For example: <li *ngFor="let product of products"> {{product.DisplayProductName}} </li> ... export class Public ...

typescriptIn React Router v5 with TypeScript, an optional URL parameter is implemented that can have an undefined

I'm currently working with react-router v5.1 and TypeScript, and I have set up the following route configurations: <Router basename="/" hashType="slash"> <Switch> <Route path="/token/:tokenName"> <TokenPag ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Using TypeScript to Import Modules without Default Exports (CommonJS)

Can a module that is defined without a default export be imported using import module from 'module'; and then compiled to commonjs? An answer on Stack Overflow suggests that it might be possible with the use of the --allowSyntheticDefaultImports ...

Prevent specific dates on Angular Mat Calendar by utilizing Rest API response

I am currently working with the Angular material calendar, specifically the mat-calendar component. My goal is to dynamically disable certain dates in the calendar based on specific values. HTML <mat-calendar [headerComponent]="exampleHeader" [dat ...