Angular2 HTTP GET-将响应转换为完整对象 [英] Angular2 HTTP GET - Cast response into full object
问题描述
我有这个简单的组件
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);
}
}
为什么subscribe
不将响应转换为完整的User
对象.当我记录user
变量时,在控制台上说User {_id: undefined, name: undefined, surname: undefined, email: undefined}
.但是尽管如此,绑定到视图中的.name
和.surname
仍然有效.
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?
推荐答案
在此处找到了解决方案: https://stackoverflow.com/a/29759472/2854890
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);
});
}
我通过最后返回对象来增强了Serializable
,因此我可以省略
I enhanced the Serializable
by returning the object in the end, so I can leave out something like
var u = new User();
u.fromJSON(...);
然后写
new User().fromJSON(json);
Serializable
类
Serializable
class
export class Serializable {
fromJSON(json) {
for (var propName in json)
this[propName] = json[propName];
return this;
}
}
这篇关于Angular2 HTTP GET-将响应转换为完整对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!