0

This is my json response. How can bind the rewards.rewardName value in [(ngModel)] in angular 2.

 [
  {
   "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"
   }
 ]

This is my code buddy how can i bind the value in 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;
   });
I am Naresh
  • 175
  • 1
  • 2
  • 10

2 Answers2

1

Parse your json to an object.

var obj = JSON.parse(json);

Then bind it to your element

[(ngModel)]="obj.rewards.rewardName"
argoo
  • 1,428
  • 12
  • 17
  • i got this error buddy what can i do ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'rewardName' of undefined TypeError: Cannot read property 'rewardName' of undefined at Object.View_RewardseditComponent_0.co [as updateDirectives] (ng:///AppModule/RewardseditComponent.ngfactory.js:1152:37) – I am Naresh Apr 21 '17 at 12:33
  • Missed that obj will be an array here. try: `var arr = JSON.parse(json); var obj = arr[0];` To get the first element. – argoo Apr 21 '17 at 12:43
  • i got this error dude ERROR Error: Uncaught (in promise): SyntaxError: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () – I am Naresh Apr 21 '17 at 13:01
  • 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; }); – I am Naresh Apr 21 '17 at 13:07
  • You are already parsing the json by doing `map(res => res.json()` if "this.item" is the object you are binding to remove `var arr = JSON.parse(item);` and try `this.item = item[0];` – argoo Apr 21 '17 at 13:18
1

I would suggest that you take a look at the official http tutorial. I would suggest you use either promises or observables. Seems you would like to use promises, so I'll set up that example for you. Also please consider using a service (like in the tutorial), that is recommended, but here I'll use your existing code:

// 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];
   })

When this is done, there will be an undefined issue since this is asynchronous. Check this one: Cannot read property "totalPrice" of undefined Two-way-binding, i.e [(ngModel)] doesn't support the safe navigation operator, so you'd want to split this to one-way-binding and ngModelChange:

<input [ngModel]="item?.rewards?.rewardName" 
    (ngModelChange)="item?.rewards?.rewardName ? item.rewards.rewardName=$event : null" > 

Props to this: https://stackoverflow.com/a/36016472/6294072

Here's a DEMO using service, which I suggest you do ;)

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167