gpt4 book ai didi

javascript - TypeScript myFunction 不是函数

转载 作者:行者123 更新时间:2023-11-28 17:04:32 25 4
gpt4 key购买 nike

我在 Angular 工作,遇到以下情况:

my.service.ts 有此类:

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

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

并且my.component.ts这样调用它:

myData: MyClass[] = [];

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

VS Code 将 createString 函数识别为 MyClass 的方法,但我仍然收到错误:

ERROR TypeError: x.createString is not a function

有什么解释吗?

编辑:数据来自后端,后端模型没有此方法。也许这就是问题所在?

最佳答案

来自服务器的对象只是一个简单的对象,而不是类MyClass的实例。您可以创建 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());
}
});

关于javascript - TypeScript myFunction 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56233927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com