我正在使用Angular 2并正在进行API调用以获取一些JSON。通话有效,我得到了回复。
export class DetailsPage {
public userID;
v: any = {};
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
this.userID = navParams.get('userID');
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
let body = urlSearchParams.toString();
this.http.get('http://api.domain.com/visitor/'+this.userID, {headers:headers}).map(res => res.json()).subscribe(data => {
this.v = data.res;
});
}
}
在我的模板中,我有:
<pre>{{v | json}}</pre>
这显示了我的JSON ......
{
"user": {
"id": "794149",
"tag_name": "",
"tag_id": "0",
"tag_style": {
"color": null,
"font": null,
"style": "label-default"
}
},
但是如何显示用户的ID?
我试过..
{{ v.user.id }}
但这给了我一个错误:
Error in ./DetailsPage class DetailsPage - caused by: Cannot read property 'id' of undefined
答案 0 :(得分:6)
要绑定到对象上的属性,可以使用安全导航操作符Dynamically access object property using variable。
{{v?.user?.id}}