Is there a way to update JSON data through a post request without it getting added to the existing data?

Hello, I am currently delving into Angular2 and encountering a problem concerning RestAPI. When I send a post request to the server with a JSON file, I intend to update the existing data in the JSON file; however, what actually happens is that the new data gets appended instead. Here's an excerpt of my code:

let headers    = new Headers({ 'Content-Type': 'application/json' });
let options    = new RequestOptions({ headers: headers });    
this.http.post(url, body, options).map((res:Response) => res.json())
.subscribe((body) => body );

The original content of my JSON file is as follows:

  {
    "budget": [
      {
        "service": "electricity",
        "real_amount": 100,
        "expected_amount": 100,
        "id": 0
      }
    ]
 }

After sending the post request, the JSON file ends up looking like this:

 {
  "budger":
  {
        "service": "electricity",
        "real_amount": 100,
        "expected_amount": 100,
        "id": 0
      }
    ],
    {
        "service": "electricity",
        "real_amount": 100,
        "expected_amount": 100,
        "id": 0
      }
    ]
}

In my TypeScript file :

          import { Component, OnInit } from '@angular/core';
          import 'rxjs/add/operator/map';
          import { Injectable } from '@angular/core';
          import {Http, Headers,RequestOptions,Response} from 
         '@angular/http';
          import {ApiService} from './api.service';
          import { URLSearchParams } from '@angular/http';

         @Component({
            selector: 'app-root',
           templateUrl: './app.component.html',
          styleUrls: ['./app.component.scss']
            })
            export class AppComponent implements OnInit {

          real_amount: string;
          service: string;
          expected_amount: string;
           public data;
          public real_data;

           constructor(private http: Http) {
             }
            ngOnInit(): void {
           this.http.get("./assets/data/expected_expensives.json")
          .subscribe((data) => {
            this.data = data.json();
            console.log(data.json());
             });
             }
            updateBudget() {
            console.log(this.service +" " + this.real_amount);
              console.log(this.data.budget.length);
              for(let i=0 ; i< this.data.budget.length; i++)
              {
           if (this.data.budget[i].service === this.service)
            {
             console.log(this.data.budget[i].service);
             this.data.budget[i].real_amount=this.real_amount;
            }
         } 

 let body:any = JSON.stringify(this.data.budget);
 let url = "http://localhost:3000/budget";
 let response:any;
 let headers    = new Headers({ 'Content-Type': 'application/json' });
 let options    = new RequestOptions({ headers: headers });

  this.http.post(url, body, options).map((res:Response) => res.json())
 .subscribe((body) => body );
  }
}

In my html file :

             <div id="main">
               <div id="right_side">
                <div class="form-group row">
                  <label>Choose a service</label>
                  <select  [(ngModel)]="service">    
                    <option *ngFor="let item of data?.budget" 
                       ngDefaultControl >{{item.service}}</option>
                  </select>
                  <label>Enter an amount</label>
                  <input id="real_amount" type="text" 
                  [(ngModel)]="real_amount" ngDefaultControl>
                  <input type="submit" value="Pay" 
                  (click)="updateBudget(service,real_amount)">
                   </div>
                  </div> 
                <div id="left_side">
                   <table>
                    <thead>
                     <th>Service</th>
                     <th>Expected Expencies</th>
                     <th>Real Expencies</th>
                    </thead>
                     <tbody>
                     <tr *ngFor="let item of data?.budget">          
                      <td>{{item.service}}</td>
                      <td>{{item.expected_amount}}</td>
                       <td>{{item.real_amount}}</td>
                     </tr>        
                   </tbody>
                 </table>
           </div>
           </div>

If anyone has suggestions or solutions to provide, I'd greatly appreciate it. Thank you!

Answer №1

service.ts

import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

    export class CcDataServiceService {
 constructor(private http: Http) {
  }

      getLocalData(): Observable<any[]> {
        return this.http.get('assets/data/expected_expensives.json')
          .map(this.extractData)
          .catch(this.handleError);
      }

      getserverData(ajaxdata): Observable<any[]> {
        console.log('ajaxdata::' + JSON.stringify(ajaxdata));
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(url, ajaxdata)
          .map(this.extractData)
          .catch(this.handleError);
      }

      private extractData(res: Response) {
        const body = res.json();
        return body || [];
      }

      private handleError(error: any) {
        const errMsg = (error.message) ? error.message :
          error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        console.log('Server Error!');
        return Observable.throw(errMsg);
      }
    }

component.ts

constructor(public jsonDataService: CcDataServiceService) {
  }

  ngOnInit() {
    let thisx = this;

// if you want data from server call getserverData() else getLocalData()
        this.jsonDataService.getserverData().subscribe(
          function (success) {
            thisx.data = success;
           thisx.datahandle(success);
          },
          error => console.log('Getting Server Data Error :: ' + JSON.stringify(error)));


}
datahandle(jsonData){

console.log('check your data' + JSON.stringify(jsonData)); <-----check data
// may parse your data 

let keys = Object.keys(jsonData);
console.log(keys);
}

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

Having trouble navigating typescript's "import" syntax in conjunction with compiler options like module and choosing between esnext and commonjs?

I am facing an issue with my typescript project that includes mocha tests. Here is a snippet of how the tests start: import { assert } from "chai"; import "@material/mwc-ripple"; //I need to test a script that uses this describe("simple test", () => { ...

Transforming an array list object into a JSON array

I am dealing with an ArrayList that I need to convert to a JSON array in order to send it to the server. The required JSON format is as follows: { p:1, s:["a":1,"b":2],["a":2,"b":3],["a":3,"b":4] } Assuming I have the following: List<MyObject& ...

Using Typescript to customize the color of Ionic's Ion-checkbox

I am attempting to modify the color of the ion-checkbox using TypeScript <ion-item > <ion-label id="check1">No</ion-label> <ion-checkbox color="blue" id="box1" [(ngModel)]="todo.check1" name="check1"></ion-checkbox&g ...

A guide to implementing polymorphic serialization without the use of annotations or mixins

In the city of Jackson, we have the option to utilize certain annotations: @JsonTypeInfo @JsonSubTypes @JsonSubTypes.Type These can be used for polymorphic serialization. We have two choices: Applying these annotations directly on the data model, which ...

Angular2 marker with custom design for Google Maps

We have successfully implemented Angular2 Google Maps () and integrated Styled Google Maps using the following Plunkr: https://plnkr.co/edit/rv6udUOEedMxJejEpIW1 import { Directive } from '@angular/core'; import { GoogleMapsAPIWrapper } from &a ...

Form with placeholders

Is there a way to personalize an email using different variables, like adding special characters such as $, {}, [] around the word to indicate it's a variable? For example, {name}. I'm looking for a plugin compatible with Angular 14+ that can ass ...

Challenges with synchronizing the scope of global arrays when reading JSON files into objects

I'm attempting to load a JSON file into a global array of objects. The code appears to be functioning correctly, however, I am encountering difficulty extracting the data from the Ajax $.getJSON call and storing it in the global variable. This issue c ...

Display customizable template according to variable

The answer provided for the issue regarding dynamic template generation based on value instead of variable in this thread was really helpful. However, I'm facing challenges in getting it to work. Here's a simplified example: export class A { } ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

What is the best way to set up a FormGroup when the FormControlName is dynamic and subject to change?

Hello, I am new to Angular and encountering a particular scenario. On my HTML page, there is a form (formgroup) with a div inside it that uses the ngFor directive to iterate through an object as needed. Let's say there is an input field with formCon ...

Is it still relevant to use the href attribute in Angular development?

Is there any specific benefit to either including or excluding the href attribute on internal links within an Angular 7 single-page application? Regardless, the functionality remains intact as Angular primarily relies on the routerLink attribute. ...

Ways to incorporate a dictionary into your website's content

I am in the process of developing a website for educational purposes while also honing my web programming skills. On this website, I have encountered some complicated terms that may be difficult for users to understand, so I want to implement a tooltip/mod ...

Angular 2 router generates incorrect URLpaths

When navigating through my routes, I encountered an issue with the following routing setup: const routes: Routes = [ { path: '', component : HomeComponent, children: [] }, { path: 'login', ...

Navigating with Angular router in a Bootstrap navigation bar

My link is not displaying as a tab (I'm using Bootstrap 4 and Angular 5). Instead, it shows up as just a plain link. This seems like it should be a simple issue, but this is my first time working with bootstrap... Thank you! <div> <nav cla ...

Issue with TypeScript: Assigning type 'type' to 'IntrinsicAttributes & type & { children?: ReactNode; }' is not allowed. What is the solution?

I'm currently working on a small home project to enhance my skills in TypeScript. Everything was running smoothly with retrieving data from the server and displaying posts without any errors. However, when I decided to separate the code with the map i ...

The role of providers in Angular applications

After creating a component and service in my project, I followed the documentation's instruction to include the service in the providers metadata of the component for injection. However, I found that it still works fine even without mentioning it in t ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

Identify the primary application using a hybrid application

I am currently working on a project to create a desktop application using angular2 and Electron that can run seamlessly across different platforms. One of my main challenges is being able to identify the foreground process running on the computer, regardle ...

Error encountered: "Localhost at VScode is refusing port 8080 for Cold

After coding in Visual Studio Code, I encountered an issue where Chrome debug was not connecting to localhost. How can I resolve this problem by adjusting the settings in launch.json? Check out the code snippet from launch.json below: // Use IntelliSense ...

When integrating ng2-bootstrap in Angular 2 RC 6, an issue arises where binding to a specific property is not recognized because it is not a known property of the specified element

I'm a newcomer to Angular 2 (RC 6) and I've encountered an issue while working with ng2-bootstrap. Despite RC 6 being recently released, I believe the problem lies more in my implementation rather than a bug. My goal is to replicate a basic demo ...