typescript 打字稿类中的方法给出错误“不是函数”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42899570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method in typescript class give error "is not a function"
提问by erikscandola
I work on Angular2 web application. I created a simple class in typescript:
我在 Angular2 Web 应用程序上工作。我在打字稿中创建了一个简单的类:
export class User {
firstName: string;
lastName: string;
nominative() : string {
return this.lastName + " " + this.firstName;
}
}
When i call nominative
on object of type User
I receive this error: Error in :0:0 caused by: user.nominative is not a function
.
当我调用nominative
类型的对象时,User
我收到此错误:Error in :0:0 caused by: user.nominative is not a function
。
I call the function in my AppComponent
class:
我在AppComponent
课堂上调用函数:
export class AppComponent implements OnInit {
name: string = "";
ngOnInit() : void {
let user = JSON.parse(sessionStorage.getItem("User")) as User;
if (user) {
this.name = user.nominative();
}
}
}
I already tried to use lambda expression in this way:
我已经尝试以这种方式使用 lambda 表达式:
nominative = () : string => { ... }
But nothing change. The problem is only in this class, so what am I doing wrong?
但什么都没有改变。问题只在这个班级,那我做错了什么?
采纳答案by Günter Z?chbauer
as User
only tells the compiler that it's safe to assume that the value is of type User
, but doesn't have any effect on runtime and it won't have any methods because methods are not passed with JSON.
as User
只告诉编译器可以安全地假设该值是 type User
,但对运行时没有任何影响并且它不会有任何方法,因为方法不是通过 JSON 传递的。
You would need
你需要
let user = new User(JSON.parse(sessionStorage.getItem("User")));
to get an actual User
instance. You would need to create a constructor that assigns the values from JSON to fields like
得到一个实际的User
实例。您需要创建一个构造函数,将 JSON 中的值分配给像这样的字段
class User {
...
constructor(json:any) {
this.firstName = json.firstName;
this.lastName = json.lastName;
}