在角度2中绑定ngModel中的json值
这是我的json响应。如何能在角2在角度2中绑定ngModel中的json值
[
{
"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)]
的rewards.rewardName值绑定这是我的代码哥们我怎么能值绑定在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;
});
我建议你看一看的official http tutorial。我建议你使用promise或observables。似乎你想使用承诺,所以我会为你设置这个例子。也请考虑使用服务(如在本教程),该建议,但在这里,我将使用现有的代码:
// 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服务,我建议你做;)
解析您的JSON的对象。
var obj = JSON.parse(json);
然后将其绑定到你的元素
[(ngModel)]="obj.rewards.rewardName"
我得到这个错误哥们我能做些什么 错误错误:未捕获的(在承诺未来e):TypeError:无法读取undefined属性'rewardName' TypeError:无法在Object.View_RewardseditComponent_0.co [as updateDirectives](ng:///AppModule/RewardseditComponent.ngfactory.js:1152)读取未定义的 属性'rewardName' :37) –
错过了这个obj将会是一个数组。 尝试: 'var arr = JSON.parse(json); var obj = arr [0];' 获取第一个元素。 – argoo
我得到这个错误的家伙错误错误:未捕获的(在承诺):语法错误:意外的标记?在JSON在位置1 语法错误:意外的标记?在JSON在位置1 在JSON.parse(
非常感谢我的工作 –
没问题,很高兴我能帮帮我 :) – Alex