[英]TypeScript myFunction is not a function
I am working in Angular and I have a following situation: 我在Angular工作,遇到以下情况:
my.service.ts has this class: my.service.ts具有此类:
export class MyClass {
MyList: string[] = [];
MyString: string = '';
createString(): void {
this.MyList.forEach(s => {
this.MyString += s + ', ';
});
}
}
And my.component.ts calls it like this: 而my.component.ts这样称呼它:
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: VS Code将createString
函数识别为MyClass
,但仍然出现错误:
ERROR TypeError: x.createString is not a function 错误TypeError:x.createString不是函数
Any explanations? 有什么解释吗?
EDIT : The data comes from back end, and the back end model doesn't have this method. 编辑 :数据来自后端,并且后端模型没有此方法。 Maybe that is the issue? 也许是问题所在?
The object coming from the server will be just a simple object not an instance of the class MyClass
. 来自服务器的对象将只是一个简单的对象,而不是MyClass
类的实例。 You can create instances of MyClass
and assign the values from the server object to the instance of the class: 您可以创建MyClass
实例,并将服务器对象中的值分配给该类的实例:
this.myService.getMyData().subscribe(res => {
myData = res.map(o => Object.assign(new MyClass(), o));
if (myData.length > 0) {
this.myData.forEach(x => x.createString());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.