Reputation: 171
I have a class model defined as User in the following way:
export class User {
private code: string;
get Code(): string {
return this.code;
}
public setCode($code: string) {
this.code = $code;
}
In the main component I have a part like this:
export class AppComponent {
title = 'app';
private $user: User;
constructor(private _http: HttpClient, private router: Router) {
this.loadUser();
}
public loadUser(): void {
this._http.post<User>(Global.url + '/user/show',
{}).subscribe(
data => {
if (null !== data) {
this.$user = data;
console.log(this.$user);
} else {
this.router.navigate(['/login']);
this.$user = null;
}
}
);
}
public get User(): User {
return this.$user;
}
}
The page to open makes a query of the user, the server returns the code in json format and should map it with the User Class. This is what it returns:
{…}
code: "B1039"
...
__proto__: Object { … }
But if I try to access the values through the properties "console.log(this.$user.Code)", this is what returns me:
undefined
That is to say, although in my IDE it takes that the variable data is of the type User Class, the methods to access do not work.
Why is not the json returned not converted to the User object?
I need to use a model class but not an interface.
Upvotes: 1
Views: 2090
Reputation: 2977
I preferred a safer way to do it
export class AppComponent {
private _user: User;
constructor(private _http: HttpClient) {
}
getUser(): Observable<User>{
return new Observable(observable => {
if(!!this._user){
observable.next(this._user);
observable.complete();
}
else{
this._http.get<UserResponse>('...some....')
.map(this._mapUserResponse)
.subscribe((mapped:User) => {
this._user = mapped;
observable.next(this._user);
observable.complete();
}, err => {
observable.error();
});
}
});
}
private _mapUserResponse(response:UserResponse):User{
if(!!response && !!response.foo){
return new User(response.foo, response.bar);
}
return void 0;
}
}
Upvotes: 0
Reputation: 4897
You need to call the constructor yourself. Casting <Something>data
doesn't call it for you, it only describes for the TS compiler which interface the data should look like. So for instance you could do:
this.user = Object.assign(new User(), data);
Or a common way is to make that same assignation in the class constructor, so you can just new User(data)
.
Upvotes: 1