Send JSON data to an API using Angular

I have a route with POST Method 'http://localhost:5000/cities' where I can send json data like

[{ "id:" 1, "name": "LA", "country": "USA", "value": 10000 }]

In Angular, there is a service (cities.service.ts) responsible for posting this data

export class CitiesService {

constructor() { }

send_cities(data): Observable<Result> {
return this.post(this.Url(), data);
      }
}

There is also a component (cities.component.ts) that utilizes this service

let city_code = this.form.value;
swal({
    title: '',
    text: '',
    type: 'info',
    showCancelButton: true,
    closeOnConfirm: false,
    showLoaderOnConfirm: true
  }, function () {
    self.citiesService.send_cities(city_code, self._city.id, self._city.name, self._city.country, self._city.value).subscribe(
      response => {
        swal({
          title: "",
          text: "",
          type: "success",
          timer: 1500,
          showConfirmButton: false
        });

What is the best way to post data in json format to the api as demonstrated in the example?

Answer №1

When implementing your method, make sure to pass an array containing the desired information. Here's a slight modification to help you achieve this:

swal({
    title: '',
    text: '',
    type: 'info',
    showCancelButton: true,
    closeOnConfirm: false,
    showLoaderOnConfirm: true
  }, function () {
    self.citiesService.send_cities([{self._city.id, self._city.name, self._city.country, self._city.value}]).subscribe(
      response => {
        swal({
          title: "",
          text: "",
          type: "success",
          timer: 1500,
          showConfirmButton: false
        });

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

A glitch was encountered during the execution of the ionic-app-scripts subprocess

I recently started using Ionic 3 and created an application that I'm trying to convert into an APK. To generate a debug (or testing) android-debug.apk file, I used the following CLI command: ionic cordova build android --prod The pages are declared ...

Exploring the possibilities of developing WebComponents within Angular using TypeScript

My Angular application was originally created using the default method with ng new project-name". However, for performance reasons, I had to incorporate single standard WebComponents. The JavaScript code associated with these components is stored in a ...

Developing a node module that includes nested subfolders

I'm currently working on an npm module and have the following index.ts file: export * from './src/A/index'; Right now, when importing in my app, it looks like this: import {something} from 'myModule'; Now, I want to enhance my ...

Creating a multi-level JSON object from a string: A step-by-step guide

I've organized my HTML file in the following structure: Chapter 1.1 1.1.1 interesting paragraph 1.1.1.1 interesting paragraph Chapter 1.2 1.2.1 interesting paragraph 1.2.1.1 interesting paragraph ... Chapter 11.4 ... 11.4.12 interesting ...

Information has been stored in the database after being updated in an

I have a field that can be edited and I want to save the changes to the database. Here is the relevant HTML code: <ng-container *ngIf="groupedVolumes"> <ng-container *ngFor="let model of groupKeys() | slice:-3" > ...

Angular 5 experiences a single catchError event for two unsuccessful http calls

I recently implemented Observable.zip in my code to manage multiple observables concurrently. Observable.zip(observable1, observable2).subscribe(([res1, res2]) => doStuff()) The observables observable1 and observable2 represent HTTP requests, and I ha ...

convert a string to JSON format using Node.js Express

Currently, I am viewing some string data in a browser that has been processed using python-node js express. The data looks something like this: In order to manipulate the data more effectively, I would like to convert it into JSON format that follows this ...

Internet Explorer is requesting to download my JSON response, while other browsers are functioning normally

Through my research, it seems that the problem lies in the way the headers are set for the response. The application is built on the Zend framework, and here are the specific headers that are being set (this pertains to a file upload): $response -> ...

Differentiating between missing fields and fields explicitly set to null during Gson deserialization

My current project involves incorporating JSON Merge Patch into a Java (JAX-RS) webservice that I am developing. The concept involves updating a record partially by sending a JSON document to the server that only includes the fields to be modified. For e ...

My npm init script is failing to work properly. What steps can I take to troubleshoot

I am encountering an issue while setting up a new node.js project and attempting to generate the package.json file. As a Windows user, I am utilizing Visual Studio Code terminal for my project setup. However, when I enter the command npm init, I am faced w ...

Encountering a 'System.IO.FileLoadException' when using newtonsoft-json

When I try to use the toJSONString() method in my dll assembly in Visual Studio, the debugger keeps throwing a 'System.IO.FileLoadException' error in the output window. I included the newtonsoft-json.dll library via NuGet, so it's puzzling w ...

Tips for retrieving the 'Created' value in vue.js

I am currently trying to fetch API JSON data for a weather widget, but unfortunately it is returning null. While I am able to retrieve the JSON data successfully, I am struggling to handle this value. Below is my HTML code snippet: <html> <head& ...

React-router-dom PrivateRoute component version 6.8.0

I have created a custom PrivateRoute for my chat app. This is how my PrivateRoute looks: import { useState, useEffect } from 'react'; import { Route, Navigate } from 'react-router-dom'; import axios from 'axios'; interface Pr ...

Having trouble resolving the error "Can't find 'rxjs/Rx'"?

Compilation unsuccessful. Issue with ./src/app/services/admin.service.ts Module not located: Error encountered - Unable to find 'rxjs/Rx' in 'C:\project\test-m\angular\src\app\services' Solution found in ...

In Angular, how do outputs impact parents when data consistently travels down from the root?

I have a question that may seem simple, but I am really trying to understand unidirectional data flow in Angular thoroughly. If change detection always happens from top to bottom, how does @Output impact a parent component? Could I be mistaken in my assu ...

Steps for setting up a nested route in Angular 2

I am currently working on a project that includes an admin page (check the file structure below). I am trying to set up a child route named 'createuser' for the admin page (localhost:4200/admin/createuser). Despite my attempts, I encountered an e ...

The Apollo client's GraphQL query encountered an unforeseen termination of the JSON input stream

I have customized my NextJS site with WP WooCommerce integration. By default, the query result only returns up to 100 items, but I have increased it to 1000 without any issue. When I send a request with a query like this: query MyQuery { products(fir ...

Adding a new line in the configurations of MatDialogConfig (Angular)

Here is a code snippet: private mDialog: MatDialog, const dialog = new MatDialogConfig(); msg = "I enjoy coding in Angular.\r\n I am learning TypeScript." dialog.data = { message:msg }; alert (msg); mDialog.open(AB ...

Create a POST request following a GET request and handle it in Angular 2

I am in the process of developing a service that involves both GET and POST requests to be used within a component. My question is, what would be the most effective approach to achieve this? authentication.service.ts getToken() { return this.http.get ...

Implementing a post method in Angular without a request body

I've been attempting to send a JSON request and handle the response, but I keep encountering these errors: zone-evergreen.js:2952 OPTIONS http://'api':10050/api/content/Delivery net::ERR_EMPTY_RESPONSE core.js:6014 ERROR HttpErrorResponse ...