dzenesiz
dzenesiz

Reputation: 1542

TypeScript myFunction is not a function

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?

Upvotes: 1

Views: 4039

Answers (2)

mjacob
mjacob

Reputation: 1

Accepted soulution didn't help me, so I propose mine. It does not require .map().

My http service:

getOffers() {
    return this.http.get('https://ohipo.pl/assets/oferty.json');
  }

Consuming service in component:

offers: Offer[] = [];

this.offersService.getOffers().subscribe((response: Offer[]) => {

      for (let i in response) {
        this.offers[i] = Object.assign(new Offer(), response[i]);
      }

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

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

Upvotes: 6

Related Questions