Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(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 current code. I need help with binding 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;
   });

Answer №1

If you're looking for guidance on handling HTTP requests in Angular, I recommend checking out the official http tutorial. You have the option to use either promises or observables, but based on your preference for promises, I'll provide an example using that approach. While it's advisable to utilize a service as shown in the tutorial, I will work with your existing code in this instance:

// Remove "this.itemPromise = " and below is the revised code
this.http.get('http://localhost:8080/dy/get-goal?id=' + params['id'])
   .toPromise()
   .then(res => res.json())
   .then(data => {
      this.item = data[0];
   })

After implementing this, you may encounter an issue with undefined values due to the asynchronous nature of the operation. Refer to this resource for more insights: Cannot read property "totalPrice" of undefined. Since two-way binding like [(ngModel)] doesn't support the safe navigation operator, you should consider separating it into one-way binding and ngModelChange event handling:

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

Kudos to this informative post:

For a practical demonstration utilizing a service, check out this DEMO, which aligns with my recommendation ;)

Answer №2

Transform your json data into an object.

let object = JSON.parse(jsonData);

After that, connect it to your specific element.

[(ngModel)]="object.rewards.rewardName"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the form field is double-clicked, it automatically populates with information, but unfortunately it does not meet the

Presented below is a formgroup configuration: this.order = new FormGroup({ City: new FormControl('', Validators.required), Street: new FormControl('', Validators.required), DateOfDelivery: new FormControl('', Vali ...

Utilizing React Router with Material-Table for Efficient Column Value Filtering

Is there a way to dynamically pass Route params into the filtering fields of a React table component? I am currently utilizing the material-table component and have a list of links structured like this: <ul> <li> <Link to="/Products/ ...

Quitting a program automatically in Java after a specific duration

Currently developing a Selenium program in Java and facing an issue with the code snippet below: driver = new FirefoxDriver(); The challenge arises when executing this line without an internet connection, causing the program to hang for several minutes b ...

Error: Cannot convert a value of type java.lang.String to a JSONObject in JavaJSONException

I just started exploring android development and stumbled upon an app that would complement the web scraper I've been diligently working on. This app fetches information from a MySQL database using a PHP script and presents it on your android device. ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Experiencing Difficulty Retaining Checkbox State Using LocalStorage Upon Page Reload

At the moment, I have a script that automatically clicks on a random checkbox whenever the page loads or refreshes. Through localStorage, I can also view the value of the input assigned to the randomly selected checkbox. However, I'm facing an issue ...

Working with arrays containing numerical keys in JSON using jQuery

If I have a PHP file that generates JSON data with numerical keys like this: <?php $array[1] = "abcd"; $array[2] = "efgh"; $array[3] = "1234"; $array[4] = "5678"; echo json_encode($array); ?> How can I access the value associated with key 4? The i ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

Limiting the zoom in three.js to prevent object distortion caused by the camera

I'm currently in the process of developing a three.js application where I have successfully loaded my STL objects and incorporated 'OrbitControls'. However, I am encountering an issue when attempting to zoom using the middle scroll button on ...

simulating interaction with databases within API routes

I am currently working on developing a full stack application using NextJS along with a MySQL database. Within my API routes, I interact with this database by making calls to various functions such as createOne(), which is responsible for creating new inst ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

New way to manipulate JSON data in Node.js without using XSLT

My previous experience involved using XML / XSLT for transforming xml data into various formats and ensuring it adheres to specific patterns outlined in XSD. I found this process to be incredibly powerful. However, with the shift towards handling primarily ...

Issue with animation transition not triggering on initial click

I am currently working on creating an animation for a form using JS and CSS. Here is the code snippet I have: var userInput = document.getElementById("login-user"); var userLabel = document.getElementById("user-label"); // User Label Functions funct ...

Unraveling the intricacies of the relationship between `extends` and function types in TypeScript

Example 1 seems clear to me type A = (1 | 2 | 3) extends (infer I) ? [I] : never; // A = [1 | 2 | 3] In Example 2, the type variables are being intersected but I'm unsure why type A = ( ((_: 1) => void) | ((_: 2) => void) | ((_: 3) => ...

Tips on how to loop through every piece of information within a table

<table class="table_style" id="table"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Email</th> <th>Phone</th> </tr> </thead> <tbody> ...

How can I trigger an API call 30 seconds after my React Native app switches to the background?

Seeking assistance with my React Native app: I am trying to make an API call 30 seconds after the app goes into the background. I am using AppState from react-native to detect when the app goes into the background, but I'm not receiving any callback a ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

When the modal is closed, the textarea data remains intact, while the model is cleared

My challenge involves a simple modal that includes a text area. The issue I am facing is resetting the data of the textarea. Below is the modal code: <div class="modal fade" ng-controller="MyCtrl"> <div class="modal-dialog"> <d ...