我有一个打字稿课:
export class User {
id: number;
userName: string;
knownAs: string;
age: number;
gender: string;
created: Date;
lastActive: Date;
photoUrl: string;
city: string;
country: string;
surname: string;
givenname: string;
get fullName(): string {
return `${this.givenname} ${this.surname}`;
}
sayHello() {
console.log(`Hello, my name is ${this.surname} ${this.givenname}!`);
}
}
我有一个服务功能:
user: User;
this.userService.getUser(this.loggedUser.nameid).subscribe((user: User) => {
this.user = user;
this.user.givenname = this.loggedUser.given_name;
this.user.surname = this.loggedUser.family_name;
console.log(this.user.fullName);
this.user.sayHello();
});
控制台中的结果: console.log(this.user.fullName)=未定义 this.user.sayHello(); =错误TypeError:对象不支持属性或方法“ sayHello”
从服务器取回用户数据后,如何访问在用户类中定义的属性和函数?
答案 0 :(得分:1)
尝试像这样为prototype
创建一个User
对象。从服务中获得的User
可能不是prototype
对象,因此它上的功能不可用。
user: User;
this.userService.getUser(this.loggedUser.nameid).subscribe((user: User) => {
this.user = Object.assign(new User, user) //-->notice the use of new here..
this.user.givenname = this.loggedUser.given_name;
this.user.surname = this.loggedUser.family_name;
console.log(this.user.fullName);
this.user.sayHello();
});
更新: JavaScript类并非完全是面向对象的模型。根据MDN:
在ECMAScript 2015中引入的JavaScript类主要是语法糖,而不是JavaScript现有的基于原型的继承。类语法不会向JavaScript引入新的面向对象的继承模型。
了解更多here
此外,正如@theMayer在评论中指出的那样,返回user
的服务还可以返回具有原型功能的正确User
对象。因此,从客户端到服务创建对象的代码置换。我喜欢这种方法,只是因为这意味着服务的任何其他使用者都可以使用对象行为(函数),而不必复制(Object.assign
)对象。
因此,在UserService.ts
(或定义userService
的任何地方)中,类似:
getUser(id: string):User {
//existing logig
return Object.assign(new User(), user)//--> there are other ways to create object too, this is just one way.
}
答案 1 :(得分:1)
您没有创建User的实例。
这是一个如何实现的示例:
export class User {
id?: number;
userName?: string;
knownAs?: string;
age?: number;
gender?: string;
created?: Date;
lastActive?: Date;
photoUrl?: string;
city?: string;
country?: string;
surname?: string;
givenname?: string;
constructor(args: User = {}) {
this.id = args.id;
this.userName = args.userName;
this.knownAs = args.knownAs;
this.age = args.age;
this.gender = args.gender;
this.created = args.created;
this.lastActive = args.lastActive;
this.photoUrl = args.photoUrl;
this.city = args.city;
this.country = args.country;
this.surname = args.surname;
this.givenname = args.givenname;
}
get fullName(): string {
return `${this.givenname} ${this.surname}`;
}
sayHello() {
console.log(`Hello, my name is ${this.surname} ${this.givenname}!`);
}
}
使用map创建您的用户实例:
user: User;
this.userService.getUser(this.loggedUser.nameid)
.pipe(map((user: User) => new User(user)))
.subscribe((user: User) => {
this.user = user;
this.user.givenname = this.loggedUser.given_name;
this.user.surname = this.loggedUser.family_name;
console.log(this.user.fullName);
this.user.sayHello();
});