Daniel Hitzel Daniel Hitzel - 3 years ago 235
TypeScript Question

Angular2 HTTP GET - Cast response into full object

I have this simple Component

import {Component} from 'angular2/core';
import {RouterLink, RouteParams} from 'angular2/router';
import {Http, Response, Headers} from 'angular2/http';
import {User} from '../../models/user';
import 'rxjs/add/operator/map';


@Component({
template: `
<h1>{{user.name}} {{user.surname}}</h1>
`,
directives: [RouterLink],
})
export class UserComponent {

user: User;

constructor(private routeParams: RouteParams,
public http: Http) {
this.user = new User();
this.http.get('http://localhost:3000/user/' + this.routeParams.get('id'))
.map((res: Response) => res.json())
.subscribe((user: User) => this.user = user);
console.log(this.user);
}
}


Why does
subscribe
not cast the response into a full
User
object. When I am logging the
user
variable my console say
User {_id: undefined, name: undefined, surname: undefined, email: undefined}
. But nevertheless binding to
.name
and
.surname
in the view is working..

What happens here? Where is the user actually stored?

Answer Source

Found a solution here: https://stackoverflow.com/a/29759472/2854890

My Method now looks like this:

constructor(private routeParams: RouteParams,
    public http: Http) {
    this.user = new User();
    this.http.get('http://localhost:3000/user/' + this.routeParams.get('id'))
        .map((res: Response) => res.json())
        .subscribe((json: Object) => {
            this.user = new User().fromJSON(json);
        });
}

I enhanced the Serializable by returning the object in the end, so I can leave out something like

var u = new User();
u.fromJSON(...);

and just write

new User().fromJSON(json);

Serializable class

export class Serializable {

    fromJSON(json) {
        for (var propName in json)
            this[propName] = json[propName];
        return this;
    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download