TypeScript myFunction is not a function

Issue

I am working in Angular and I have a following situation:

my.service.ts has this class:

export class MyClass {
    MyList: string[] = [];
    MyString: string = '';

    createString(): void {
        this.MyList.forEach(s => {
            this.MyString += s + ', ';
        });
    }
}

And my.component.ts calls it like this:

myData: MyClass[] = [];

this.myService.getMyData().subscribe(res => {
    myData = res;
    if (myData.length > 0) {
        this.myData.forEach(x => x.createString());
    }
});

VS Code recognizes the createString function as a metod of MyClass, but I still get an error:

ERROR TypeError: x.createString is not a function

Any explanations?

EDIT: The data comes from back end, and the back end model doesn’t have this method. Maybe that is the issue?

Solution

The object coming from the server will be just a simple object not an instance of the class MyClass. You can create instances of MyClass and assign the values from the server object to the instance of the class:

this.myService.getMyData().subscribe(res => {
    myData = res.map(o => Object.assign(new MyClass(), o));
    if (myData.length > 0) {
        this.myData.forEach(x => x.createString());
    }
});

Answered By – Titian Cernicova-Dragomir

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published