Unable to retrieve a method from the model class in Angular 4

I attempted to utilize a method from the model class, but encountered an error:

ERROR TypeError: act.sayHi is not a function

Below is my code snippet:

Model Class myModelClass.ts

    export interface IMymodel {
        name: string;
        address: string;
        age: number;
    }

    export class Mymodel implements IMymodel {
        name: string;
        address: string;
        age: number 

        constructor() {}

        sayHi(name): string {
            console.log('Hiii' + name);
            return 'Hiii'+name;
        }

    }

Component MyComponent.ts

import { IMymodel, Mymodel } from '../model/myModelClass.ts';

@Component({
    selector: 'my-component',
    templateUrl: 'myComponent.html'
})
export class MyComponent {

    ...

    prepareData(data: Array<IMymodel>): Array<IMymodel> {

         data.map((act: Mymodel) => {
             act.sayHi(act.name);
         });

         return data;
    } 

}

Answer №1

In order to properly access your objects through an interface type, you must include the sayHi method signature in the interface as well. This is necessary because the interface type does not have a method named sayHi.

export interface IMymodel {
    name: string;
    address: string;
    age: number;
    sayHi(name): string
}

This also applies when making method calls.

prepareData(data: Array<IMymodel>): Array<IMymodel> {

     data.map((act: IMymodel) => {
         act.sayHi(act.name);
     });

     return data;
} 

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

Testing Angular Library Before Release

My Angular library consists of modules, each containing services. I am looking for a way to easily test my library when I make changes to one of the services. Is there a simple solution that doesn't involve publishing and installing it in the main pr ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

What is the best way to access the vue3datepicker object in order to manually close the date picker popup user interface?

Enhancement After yoduh's feedback, I made adjustments to the code below. However, vue3datepicker is still undefined. Code has been updated according to yodubs suggestion. I consulted the official vue3datepicker documentation to customize my own Act ...

Decorating AngularJS' ExceptionHandler with TypeScript is not feasible because a function is not identified as such

Scenario: In the project I am currently involved in, there has been a transition from utilizing AngularJS (1.6.2) with JavaScript to TypeScript 2.1.5. We had implemented a decorator on the $exceptionHandler service which would trigger a call to a common ...

The Semantic UI Tabs in Angular 4 only function properly once they have been clicked on

I have set up semantic UI tabs in my app.component.html as shown below: <div class = "ui container"> <h1>Header/h1> <hr> <div style = "background-color: rgb(194, 221, 240);" class="ui top attached tab ...

Tips for retrieving a server-set cookie in your Angular 2 application, and guidelines for including the same cookie in requests made by your Angular 2 application

Requirement: Our application should be able to support the same user opening our web application as a separate session. The issue is not about how to use cookies in Angular 2, but rather how the server can retrieve cookies from the HTTPServletRequest obje ...

Tips for effectively managing RxJS Observables when synchronization of data is crucial

Hopefully the topic is clear enough. I am relatively new to working with RxJS and Redux. Currently, I am developing an Angular 2+ application using Observables and NgRX store. Within the store, there are multiple sections. My goal is to extract propertie ...

Utilizing stored procedures to send JSON data to Angular application

Our team is currently in the process of creating a cutting-edge browser-based user interface for our comprehensive enterprise system using Angular.js paired with the Infragistics toolset. The ASP.NET Core Web API serves as the conduit for exchanging JSON d ...

Explore the titles provided by Wikipedia

Hi there, I'm fairly new to Angular and trying to work with the Wikipedia API. However, I seem to be having trouble getting 4 titles from the API. Here's an example URL for one of the titles: https://en.wikipedia.org/w/api.php?action=query&pr ...

Child routes in Angular tabs are failing to display in the currently active tab

Hey there! I'm currently working on navigating my Angular application using tabs, and I've run into a bit of an issue with the child routes. Specifically, when I switch to the second child route within the second tab, the status of the tab change ...

Tips for arranging backend data horizontally within Bootstrap horizontal cards

After setting up my Angular application, I created a dashboard page and made API calls for dynamic signals (signal-1, signal-2, etc). To showcase this data, I decided to use Bootstrap horizontal cards. However, I'm facing an issue with displaying the ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Retrieve GPS data source details using Angular 2

In my Angular 2 application, I am looking to access the GPS location of the device. While I am aware that I can utilize window.geolocation.watchposition() to receive updates on the GPS position, I need a way to distinguish the source of this information. ...

<Click here to navigate to page 2> await whenClicked={navigation.navigate("page_2")} />

Issue with assigning a 'string' to a parameter in TypeScript while trying to navigate to another screen in React Native. Can anyone help with this error? This problem occurs when we want to navigate to another screen using TypeScript in React Na ...

Angular 4 fetches the number obtained from a GET request

In my spring-boot back-end app, I have defined a query as shown below: @Query("SELECT COUNT(*) " + "FROM Foo " + "WHERE name = :name and surname = :surname ") Integer countByNameAndSurname(@Param("name") String name, @Param("surnam ...

Angular is unable to create a new project

I attempted to create a new project using AngularCLI in the following way: ng new my-app-ambition However, this resulted in the following errors: npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning UNABLE_TO_VER ...

Tips on clearing and updating the Edit Modal dialog popup form with fresh data

This code snippet represents my Edit button functionality. The issue I am facing is that I cannot populate my Form with the correct data from another component. Even when I click the (Edit) button, it retrieves different data but fails to update my form, ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...

What is the process of incorporating a function into an object?

My current object has: public functions = { chosenYearHandler: null, chosenMonthHandler: null }; There is a method within the object: public chosenMonthHandler(normalizedYear: any) { this.form.controls["date"].setValue(normalizedYear); ...

Ion-List seamlessly integrates with both ion-tabs and ion-nav components, creating a cohesive and dynamic user interface

On my homepage, there is an ion-list. Sometimes (not every time), when I select an item in this list or navigate to the register page using "this.app.getRootNav().push("ClienteCadastroPage")", and then select an input in the registerPage or descriptionPage ...