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?
xshould be aMyClass, so VSCode lets you do completion; butxis in actuality probably just a POJO.myData.length > 0is 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.lengthcheck - there is a lot of unnecessary code. TheforEachincreateStringcan just be replaced withthis.MyList.join(", ")and theforEachfor callingcreateStringalso strikes me as unnecessary - thestringproperty 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.