![](/img/trans.png)
[英]How to create Angular 5 HttpClient instance in Typescript class
[英]Angular TypeScript class instance
我有一個打字稿課:
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'
從服務器取回用戶數據后,如何訪問在用戶類中定義的屬性和函數?
嘗試像這樣為User
創建prototype
對象。 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引入新的面向對象的繼承模型。
在這里閱讀更多
而且,正如@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.
}
您不是要創建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: 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();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.