Uh oh, it looks like there's an issue! The function getCoordinates is not recognized for this.locations

Whenever I attempt to execute the method in my class (getCoordinates()), an Error is thrown:

ERROR TypeError: this.locations[0].getCoordinates is not a function

What am I doing wrong?

The service method I'm using:

getLocations(){
    return this.http.get<Location[]>(this.locationUrl);
  }

This is how my model looks like:

export class Location {
    id: number;
    objectTypeId: number;
    type: string;
    fields: Fields;
    fav: boolean;
    typeless: boolean;
    pages: number;
    lastmodified: string;

    public getCoordinates(): number {
        return this.id;
    }
}

export class Fields {
    city: string;
    street: string;
    company: string;
    plz: string;
    info: string;
}

And here's the component code snippet:

public locations: Array<Location> = [];

ngOnInit() {
    this.getAddresses();
  }

getAddresses() {
    this.enaioService.getLocations()
      .subscribe(data => 
        this.locations = data,
        (error: HttpErrorResponse) => this.errorMessage = error.message
      );
  }

onClick() {
    console.log(this.locations[0].getCoordinates()); // This is where the error occurs
  }
https://stackblitz.com/edit/angular-bjgtn4

Project link: https://bitbucket.org/sven_hagemann/myproject/src/master/
Clone: git clone https://[email protected]/sven_hagemann/myproject.git

Answer №1

The reason for this issue is that the list of Location objects fetched from your getLocations method are not actual instances of the Location class. Currently, you are using TypeScript syntax sugar to specify that the output of getLocations should adhere to the properties of the Location class, but it's not mandatory.

To resolve this, you should modify your code to ensure that real instances of the Location class are returned:

import {map} from "rxjs/operators";

getLocations(): Observable<Location[]>
{
    return this.http.get(this.locationUrl).pipe
    (map( (items: any[]) => items.map(i => Object.assign(new Location(), i));
    ));
 }

Answer №2

Give this a shot

fetchLocations(): Observable<Location[]>{
    return this.http.get<Location[]>(this.locationUrl)
  .pipe(map( (data: any[]) => 
   data.map(item => Object.assign(new Location(), item)); ));
}

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

picker elementClass()

I encountered an issue while using the datepicker from Material UI. The datepicker has a method called dateClass: dateClass() { return (date: Date): MatCalendarCellCssClasses => { const unvailableArray = this.shareDate.unavailableDates; ...

Issue with drag and drop functionality in Angular 13 when using ngFor with a JSON array

Embarking on my inaugural endeavor with Angular material CDK drag and drop for one of my user stories. I'm puzzled as to why an array of objects is not functioning properly in cdk drag and drop Error message: Argument of type 'CdkDragDrop<{ ...

Implementing a custom overwrite function in TypeScript's inheritance

Below is a class that I have: export class RestService { private baseUrl: string; constructor(protected http: HttpClient) { this.baseUrl = environment.LOCAL_URL; } public get<T>(resource: string, params?: HttpParams): Observable< ...

Facing the dreaded "ECONNREFUSED" error when trying to connect NodeJS and InfluxDb

I'm encountering an issue when trying to connect to my InfluxDB instance running in a Docker container. To get the InfluxDB image, I used the following command: docker pull influxdb:2.4.0 When I run it locally using Docker Desktop, everything works ...

Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume ...

What sets aws-cdk-lib apart from @aws-cdk/core, @aws-cdk/aws-iam, and others?

There seems to be a variety of examples out there using the AWS CDK, with some referencing aws-cdk-lib and others using @aws-cdk/core. Can someone clarify the distinction between these two and provide guidance on when to use one over the other? ...

Redirecting to child routes based on conditions

I encountered a situation where I need to lazily load child routes and display them conditionally: const routes: Routes = [ { path: '', component: MainComponent, canActivate: [AuthGuard], children: [ { path: &apos ...

How can I swap a string for a symbol in JavaScript?

Is there a way to convert the text @abc some text here to <a href="some_url">@abc</a> some text here using JavaScript? Are there any libraries that can help with this task? ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

Error in React-Typescript: The element type 'Component' is missing any construction or call signatures

I recently wrote a higher order component using React withContext: import React from 'react'; import permissionContext from 'context'; interface Props { Component: () => React.Component; } const withContext: React.FC<Props> ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

Incorporating redux-offline seamlessly into your Angular 5 project

I'm currently grappling with the decision of how to develop an Angular web application that can function seamlessly under offline conditions. While researching possible solutions, I came across react-offline which seems to be a reliable choice for ha ...

Recording the details of an Angular project through the utilization of Compodoc

I am currently in the process of documenting my Angular + Typescript application using Compodoc. To install Compodoc, I utilized npm and executed the following command: 'npm install -g compodoc'. And included "compodoc": "./node_modules/ ...

The id attribute is missing in ionic 2's innerHTML

I've got a script that looks like this... This is the TypeScript part: export class sampleClass { content: any; constructor(public navCtrl: NavController, public navParams: NavParams) { this.content = [ {title: "Title 1", body:"<div id ...

Leverage Custom_Pipe within TS

I am currently working with a pipe that I have created. Here is the code: @Pipe({ name: 'searchNomES' }) export class SearchNomESPipe implements PipeTransform { transform(uos: IUo[], name?: string,): IUo[] { if (!uos) return []; if (!name) ret ...

When it comes to field validations, should they be implemented on the frontend or backend? Which

In the process of creating a login and registration form, I am integrating Angular 6 for the frontend and NodeJs for the backend. I would like to gather opinions on whether it is preferable to handle field validation in Angular or in Node? ...

Adding comments in TypeScript: A quick guide

Hey there, I'm new to TS and could use some help. Here is the code snippet I have: I want to comment out the logo but adding "//" and '/*' doesn't seem to work. This is what I tried: // <LogoComponent classes={{container: style.log ...

Discovering if objects possess intersecting branches and devising a useful error notification

I have 2 items that must not share any common features: const translated = { a: { b: { c: "Hello", d: "World" } } }; const toTranslate = { a: { b: { d: "Everybody" } } }; The code ab ...

retrieving and presenting information stored in a Firebase repository

I am currently working on retrieving data from a firebase database and storing it in an array called courses that I have declared within my class. Here's the code I have so far: import { AngularFireDatabase, AngularFireList } from 'angularfire2 ...

Experimenting with HttpClient request using callFake() method

I am currently facing a challenge while trying to devise a spec for testing a method within my Angular service that initiates a GET request. The main issue I'm encountering is how to simulate the method returning an error instead of the expected respo ...