Reputation: 417
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.
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.
The error that I get is:
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
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:
<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()
}
}
Upvotes: 0
Views: 2819
Reputation: 417
I ended up defining this in my class:
static fromJSON(data: any) {
return Object.assign(new this, data);
}
Which will map the values correctly.
Upvotes: 2
Reputation: 62
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.
Upvotes: 1