我创建了一个类模型,但我不知道如何用值填充类。
User.ts
export class User {
constructor(
username: string,
password: string,
token: string
) { }
}
app.component.ts
ngOnInit() {
let user = new User('uname' , 'pword', 'sampletoken');
console.log(user);
}
运行此命令时,用户仍然是空的。
答案 0 :(得分:2)
在构造函数参数中添加访问说明符,以使其成为类属性。否则,它将仅被视为构造函数方法范围内的属性。
User.ts
export class User {
constructor(
public username: string,
public password: string,
public token: string
) { }
}
答案 1 :(得分:2)
另一种方法是您也可以这样做:-
@child_type = ChildType.find(params[:child_tye_id])
@child_list = @child_type.children
这是您可以在控制台中检查的链接。 CodeSandbox demo
答案 2 :(得分:1)
您忘记添加变量并在构造函数中分配变量:
export class User {
username: string;
password: string;
token: string;
constructor(username: string,
password: string,
token: string) {
this.username = username;
this.password= password;
this.token= token;
}
}
答案 3 :(得分:1)
尝试这样:
export class User {
username: string;
password: string;
token: string;
constructor(username: string, password: string, token: string) {
this.username = username;
this.password = password;
this.token = token;
}
}
答案 4 :(得分:0)
我将通过一个示例向您展示如何在angular中使用一个类。
items.ts
import { Injectable } from '@angular/core';
@Injectable()
export class Items {
items: Item[] = [];
defaultItem: any = {
"name": "Burt Bear",
"profilePic": "assets/img/speakers/bear.jpg",
"about": "Burt is a Bear.",
};
constructor(public name: string) {
let items = [
{
"name": "Burt Bear",
"profilePic": "assets/img/speakers/bear.jpg",
"about": "Burt is a Bear."
}
];
}
}
让我们检查如何获取这些数据
item-details.ts
import { Items } from '../../providers';
export class ItemDetailPage {
item: any;
constructor(items: Items) {
this.item = items.defaultItem;
}
}