这是我的json回复。如何在{2}中绑定[(ngModel)]
中的rewards.rewardName值。
[
{
"id": 18,
"gname": "learning ramayanam",
"goalCategory": "Education",
"goalSubCategory": "short-term",
"goalDesc": "good",
"rowStatusCode": "D",
"createID": "1",
"createTS": null,
"updateID": "Ram",
"updateTS": null,
"rewards": {
"rewardID": 1,
"rewardName": "Laptop"
}
]
这是我的代码伙伴如何绑定ngModel中的值
ngOnInit() {
this.route.params
.forEach(params => {
this.isEdition = !!params['id'];
if (this.isEdition) {
// this.getDocument(params['id']);
this.itemPromise = this.http.get('http://localhost:8080/dy/get-goal?id='
+
params['id'])
.map(res => res.json()).toPromise();
this.itemPromise.then((item: any) => {
console.log(item);
var arr = JSON.parse(item);
this.item = arr[0];
return item;
});
答案 0 :(得分:1)
我建议您查看official http tutorial。我建议你使用promises或observables。似乎你想使用promises,所以我会为你设置这个例子。另外请考虑使用推荐的服务(如教程中所述),但在这里我将使用您现有的代码:
// remove "this.itemPromise = " and just have the code below
this.http.get('http://localhost:8080/dy/get-goal?id=' + params['id'])
.toPromise()
.then(res => res.json())
.then(data => {
this.item = data[0];
})
完成此操作后,会出现undefined
问题,因为这是异步的。检查一下:Cannot read property "totalPrice" of undefined
双向绑定,即[(ngModel)]
不支持安全导航操作符,因此您需要将其拆分为单向绑定和ngModelChange
:
<input [ngModel]="item?.rewards?.rewardName"
(ngModelChange)="item?.rewards?.rewardName ? item.rewards.rewardName=$event : null" >
道具:https://stackoverflow.com/a/36016472/6294072
这是一个DEMO使用服务,我建议你这样做;)
答案 1 :(得分:0)
将你的json解析为一个对象。
var obj = JSON.parse(json);
然后将其绑定到您的元素
[(ngModel)]="obj.rewards.rewardName"