Angular2 HTTP GET - Cast response into full object

前端 未结 3 969
执笔经年
执笔经年 2020-12-03 05:26

I have this simple Component

import {Component} from \'angular2/core\';
import {RouterLink, RouteParams} from \'angular2/router\';
import {Http, Response, He         


        
相关标签:
3条回答
  • 2020-12-03 05:46

    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;
        }
    
    }
    
    0 讨论(0)
  • 2020-12-03 05:50

    That's not supported by TypeScript.

    See How do I cast a JSON object to a typescript class for more details.

    0 讨论(0)
  • 2020-12-03 05:53

    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.

    0 讨论(0)
提交回复
热议问题