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?
x
should be aMyClass
, so VSCode lets you do completion; butx
is in actuality probably just a POJO.myData.length > 0
is pointless - if it's an empty array it'll just loop over zero things, and if it's not an array the check will likely fail to find a length property.length
check - there is a lot of unnecessary code. TheforEach
increateString
can just be replaced withthis.MyList.join(", ")
and theforEach
for callingcreateString
also strikes me as unnecessary - thestring
property could just have a dynamic getter that builds the the value on demand and caches it, instead of having to call an extra method to populate it on each element and each time the observable pushes an update.