打字稿类中的方法给出错误“不是函数". [英] Method in typescript class give error "is not a function"
问题描述
我在Angular2 Web应用程序上工作.我在打字稿中创建了一个简单的类:
I work on Angular2 web application. I created a simple class in typescript:
export class User {
firstName: string;
lastName: string;
nominative() : string {
return this.lastName + " " + this.firstName;
}
}
当我在类型为User
的对象上调用nominative
时,出现此错误:Error in :0:0 caused by: user.nominative is not a function
.
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
.
我在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();
}
}
}
我已经尝试通过这种方式使用lambda表达式:
I already tried to use lambda expression in this way:
nominative = () : string => { ... }
但是什么都没有改变.问题只在这个班上,所以我在做什么错了?
But nothing change. The problem is only in this class, so what am I doing wrong?
推荐答案
as User
仅告诉编译器可以安全地假定该值的类型为User
,但对运行时没有任何影响,它将没有任何方法,因为方法未随JSON传递.
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.
您需要
let user = new User(JSON.parse(sessionStorage.getItem("User")));
以获取实际的User
实例.您将需要创建一个构造函数,将JSON中的值分配给类似
to get an actual User
instance. You would need to create a constructor that assigns the values from JSON to fields like
class User {
...
constructor(json:any) {
this.firstName = json.firstName;
this.lastName = json.lastName;
}
这篇关于打字稿类中的方法给出错误“不是函数".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!