Is there a way to update a JSON within a function in the context of API programming with Angular?

Here is the JSON data I am working with:

.json
"type": [ {
      "id": 2,
      "secondid": "1",
      "name": "f",
      "positionX": 0,
      "positionY": 0
}]

Alongside this data, I have a Service as shown below:

public updateposition(Model: typemodel): Observable<any> {
      return this.http.post(this.apiEndPoint + '/type' + '/' + typemodel.id , typemodel);
   }

Additionally, in my TypeScript file, I have declared x and y variables like so:

.ts
 x: number;
 y: number;

updateposition()
{

}

The objective is to update the "type" object within the JSON by utilizing values of x and y upon clicking a button in HTML. The HTML implementation is not an issue. However, I am unsure about how to proceed with updating the JSON object using the new x and y positions defined in TypeScript. My intention is to execute this task within the updateposition() function. Any recommendations or suggestions are greatly appreciated :)

Answer №1

To access the Service in your component and manipulate a JSON object, you must utilize Dependency Injection. With this, you can update the object in JavaScript upon a button click, followed by making an API request. Make sure to subscribe to the result for the API call to be successful.


// ...
export class MyComponent {
  public jsonObject: TypeModel = { ... };
  public constructor(private service: Service) { }

  // ...

  public function updateposition() {
    this.jsonObject[0].positionX = 52;
    this.jsonObject[0].positionY = 42;
    this.jsonObject = this.service.updateposition(this.jsonObject).subscribe(
      result => {
        console.log("The API call returned", result);
      }
    );
  }
}

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

Various JSON Tag values occurring more than once

Upon receiving a JSON Object in HTML, I am passing it to a JavaScript function defined below. The issue arises when the same folderName appears repeatedly on the HTML page. JSON Object: { "folderName": "arjunram-test", "objects": [ { ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

I encountered an error message while running the Angular JS code that I had written, and I am unable to find a solution to resolve it

Every time I attempt to run ng serve, the following error message pops up: "The serve command requires to be run in an Angular project, but a project definition could not be found." I've already experimented with various commands like: npm cache clean ...

Navigating with Angular 6 - Utilizing Query Parameters within a designated secondary router outlet

Is it feasible to implement query parameters within a secondary named router outlet in Angular 6? An illustration of the desired URL format is localhost:4200/home(sidebar:chat?animal=dog) I aspire to set the query parameter "animal" and retrieve its valu ...

Using spring web flow for efficient data transfer with ajax

After working with Spring MVC for some time, I have now ventured into using Spring Web Flow to easily create applications. My current dilemma is: I have a JSP page with textboxes that need to be filled out by the user. I want to transfer this user data to ...

Storing a variety of specification tables with varying amounts of data in a MySQL database

Managing a product database with variable specification tables can present some challenges. Each product may require different specifications, and the number of columns in these tables could vary as well. One approach to consider is using JSON as a data t ...

Managing JSON data for multiple images with different dimensions

"images": { "options": [ { "size": "small", "dimensions": [ { "width": 100, "height": 75, "link": "https://i.vimeocdn.com/video/566955426_100x75.jpg?r=pad", ...

Obtain a reference to a class using a method decorator

My goal is to implement the following syntax: @Controller('/user') class UserController { @Action('/') get() { } } Now in the definition of decorators: function Controller (options) { return function(target: any) { let id ...

What is the best way to connect an object to an array using ngFor in Angular?

It has been noticed that in Angular, the current variable does not align with the available options. Even though the object { question: 'q3', answer: '' } exists in data.questions, it may not be a direct match. Is there a method to en ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

What causes the .getJSON function to return a MIME type error when trying to access the API

I've been attempting to make a call to the Forismatic API, but I keep encountering a MIME type error when sending it. JQuery Request: $(document).ready(function() { $("#quote-button").on("click", function(){ $.getJSON("https://api.forism ...

Inquiry on SSGHelpers and GetStaticProps functionality with parameterization

I am currently implementing createProxySSGHelpers to prefetch data using trpc in a project I'm developing, but I'm facing an issue where the id from the url params is returning as undefined even though it's visible in the url bar. Below is ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

Exploring multilevel JSON data in MariaDB/MySQL to pinpoint a particular value

My current project involves working with a MariaDB table that contains a JSON value stored in the following format: {"nextValue":4,"1":{"text":"Item1","textDisplay":"","value":1,"isActive":0},"2":{"text":"Item2","textDisplay":"","value":2,"isActive":1},"3 ...

Exploring how to traverse a <router-outlet> within its container

I am attempting to switch the active component within a from its parent. After observing how Ionic achieves this, I believe it should resemble the following (simplified): @Component({ template: '<router-outlet></router-outlet>' } ...

Error encountered when implementing Angular Model Class within an array structure

In the current project, I have developed a class and am attempting to utilize the constructor format for certain content within the project. Here is my Angular class - import { Languages } from './temp-languages.enum'; export class Snippet { ...

Can a map key value be converted into a param object?

I have a map containing key-value pairs as shown below: for (let controller of this.attributiFormArray.controls) { attributiAttivitaMap.set(controller.get('id').value, { value: controller.get('valoreDefault').value, mandatory ...

Best practice for handling HTTP Post requests, followed by downloading content through HTTP, and finally saving the data to Core Data

I have a mobile application that syncs data to a server. The process involves converting local data to JSON, sending it to the server via HTTP Post, receiving and processing confirmation from the server, requesting job updates in JSON format, and saving th ...

Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable. This is the function in question: import {Observable} from &apos ...

Calculate the total by subtracting values, then store and send the data in

Help needed with adding negative numbers in an array. When trying to add or subtract, no value is displayed. The problem seems to arise when using array methods. I am new to arrays, could someone please point out where my code is incorrect? Here is my demo ...