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

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...

Discovering the version of the Javascript library utilized on a website - a step-by-step guide

My quest is to uncover the versions of JavaScript libraries being utilized by popular websites. By using phantomjs.exe, I successfully identified the version information for jquery. However, I am currently at a loss on how to expand this capability to inc ...

The FlatList component will only trigger a re-render once the list has been scrolled

I need help with updating a FlatList in my app. Currently, the list is populated by an array stored in the component's state and can be filtered using a filtering function that updates the state with a new filtered array. However, I have noticed that ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...

Is it advisable to enhance all Java Swing GUI elements with a validation feature using this approach?

As I worked on developing a GUI Swing App some time ago, I found myself creating 18 classes. Each class extends a Swing class like JTextField, JList, JTable, JTextArea, and others, while also implementing a uniform interface for data access and validation. ...

Angular 6 - Consistently returning a value of -1

I'm facing an issue with updating a record in my service where the changes are not being reflected in the component's data. listData contains all the necessary information. All variables have relevant data stored in them. For example: 1, 1, my ...

Adding quotes is optional when using the append function

We are retrieving product options from the displayed html using variables PRODUCT_CUSTOM_1_ and PRODUCT_NAME_. Some products have quotations like " and '. However, when we post these strings elsewhere, they get cut off at the ". We need to either remo ...

Access the Angular application directly from the email

Our infrastructure consists of a .NET back-end, an Angular 5 application, and a nginx server. Upon registering your account in the application, you will receive an email with a verification link structured as follows: [root]/register/verify?userId=blabla& ...

Making a JSON call to the eBay API

Struggling with sending JSON requests to the Ebay API. Here is the json request: string jsonInventoryRequest = "{" + "\"requests\": ["; int commaCount = 1; foreach (var ep in productsToProcess) { ...

Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database: $scope.submit = function(){ var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name; console.log(url); $ht ...

The Function(JS) is specifically designed to only function within the topmost div or quote

Currently, I am facing an issue with a function I have implemented. This function adds a blur effect to words in a Blockquote when the page is loaded. However, I need this function to work for all Blockquotes and different divs on the page, not just the to ...

Unable to locate module '...' or its associated type declarations. Issue encountered in NextJS with TypeScript integration

Within my NextJs project, I have generated a cookie.ts file in the utils directory. Upon running "npm run dev" and accessing my application on localhost:3000, everything runs smoothly with no errors, and the code in my utils/cookie.ts file is retrieved suc ...

Bespoke directive - Angular 2/4/5

Currently, I am using Angular 5 CLI but for some reason my custom directive is not working as expected. There are no errors showing up in the console either. I am trying to apply some styles to make the image fill the full width. Below are two different i ...

javascript retrieving JSON data through an API request from a redirected URL

I am retrieving JSON data from the Glitch API. Upon opening the link, it redirects to a different domain (the domain was changed from gomix.me to glitch.me) When using Postman for both HTTP requests, I receive identical JSON data. However, there is a d ...

how to forward visitors from one URL to another in a Next.js application

I have an existing application that was initially deployed on , but now I want to change the domain to https://example.com. What is the best way to set up redirection for this domain change? I have attempted the following methods: async redirects() { r ...

The HostListener feature ceased to function properly following an upgrade to the newest version of Angular (Version 15)

After upgrading to angular 15, I encountered an issue with the following code. The line `this.ngControl.value` is returning blank instead of the expected value. Has anyone else experienced this and found a solution? import { Directive, HostListener } fro ...

Creating variables within an AJAX 'success' callback function in JavaScript

$(document).ready(function() { $.ajax({ url: 'objects.php', type:'GET', dataType: 'json', success: function(response) { var variable = [some_arra ...

retrieving data from a dropdown selection

Help! I'm stuck and need guidance. Below is the code I've been working on, attempting to set a variable using a drop-down list. Despite trying everything I can think of, I still seem to be missing something simple. Any hints or nudges in the righ ...

Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this: <script> export default { props: ['title'], data() { return { } } } </script> After completing a specific action, I need to pro ...

Reading a CSV file using pandas, with the last column potentially containing commas

I am currently facing an issue with loading a well-formed CSV dataset using the pandas package. The header contains 5 column names and the final column consists of JSON objects with unescaped commas, like this: A,B,C,D,E 1,2,3,4,{K1:V1,K2:V2} When I try ...