[英]Map JSON to TypeScript Class using HttpClient Angular
I want to use the HttpClient to make an API call and map the response to and class (not interface), I want that class to have certain methods with i can extend and later call in the HTML views. 我想使用HttpClient进行API调用,并将响应映射到和类(不是接口),我希望该类具有某些方法,可以扩展并稍后在HTML视图中调用。
I don't know why this isn't working as expected but it seems like it isn't possible for the HttpClient to map my json to classes. 我不知道为什么这不能按预期工作,但是HttpClient似乎无法将json映射到类。
The error that I get is: test is not a function
我得到的错误是:
test is not a function
I'm trying to do this as followed: 我正在尝试这样做,如下所示:
User.ts 用户名
export class User {
id: number;
first_name: string;
last_name: string;
groups: Group[];
test() {
return 'test';
}
}
Api.Service.ts Api.Service.ts
export class ApiService {
private base_url: String = environment.api;
constructor(private http: HttpClient) { }
public me() {
return this.http.get<User>(this.base_url + `user/me`);
}
}
html: HTML:
<ng-container *ngIf="user | async; else loading; let user">
{{user.test()}}
</ng-container>
<ng-template #loading>
loading...
</ng-template>
controller: 控制器:
export class UserController implements OnInit {
user: Observable<User>;
constructor(private api: ApiService) {}
ngOnInit() {
this.user = this.api.me()
}
}
I ended up defining this in my class: 我最终在课堂上定义了这个:
static fromJSON(data: any) {
return Object.assign(new this, data);
}
Which will map the values correctly. 这将正确映射值。
You could do the following my frined: 你可以做到以下几点:
export class User {
id: number;
first_name: string;
last_name: string;
groups: Group[];
test() {
return 'test';
}
static fromJSON(json) {
const user: User = new User();
user.id = json.id;
user.first_name = json.first_name;
user.last_name = json.last_name;
user.groups = [];
json.groups.forEach(group => {
user.groups.push(Group.fromJSON(group));
});
return user;
}
} }
export class ApiService {
private base_url: String = environment.api;
constructor(private http: HttpClient) { }
public me() {
return this.http.get<User>(this.base_url + `user/me`).map(data => User.fromJSON(data.json()));
}
}
You must add the same method 'fromJSON' to the 'Group' class in order to create a new Group object from the json.groups. 您必须将相同的方法'fromJSON'添加到'Group'类中,以便从json.groups创建新的Group对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.