Angular2 HTTP GET - Cast response into full object

Viewed 67985

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?

3 Answers

Good practice is to consume data from GET response using

Observable<Model>

(regarding to Angular documentation https://angular.io/guide/http) so...

// imports

import {HttpClient} from "@angular/common/http";

// in constructor parameter list

private http: HttpClient

// service method

getUser(): Observable<User> {return this.http.get<User>({url}, {options});}

You do not need to do anything more. I consider this approach as most friendly.

Related