Guide on posting an object in Angular through HTTP Post

I am attempting to send an object named Pack to my API Rest server using my Angular service. Below is the function I have set up for this task:

save_pack(Pack: any){
    return new Promise((resolve, reject) =>{
      this.http
        .post("http://localhost:8000/save_pack",Pack)
        .subscribe(res => {
            resolve(res);
          },
          (err: any) => {
            reject(err);
          }
        )
    });
  }
}

However, I realize that the way I am currently sending Pack is incorrect. I would like to understand how to properly send Pack so that I can receive it in my API Rest and then access that received object. When using GET, I know you can do the following:

const Pack = req.query.Pack;

How can I achieve the same result with POST?

The POST function in my API Rest is as follows:

app.post('/save_pack', async (req,res) => {
    console.log(req.body)
    const Pack = req.body.Pack;
    console.log("Package: " + Pack);

    let result = await save_pack(Pack);
    res.send(result)
    return res;

})

Answer №1

One recommendation is to consider using Observables instead of Promises:

      save_pack(pack: any){
            this.httpClient.post<any>('http://localhost:8000/save_pack', pack)
 .subscribe(result => {
  console.log('result saved with success');
   }, err => {
  console.log('err saving new pack', pack);
    
   });
              
          }
        }

When it comes to the back-end, you can easily access the body data like this:

const pack = req.body.pack;

Here's a tip for implementing clean code: always specify a type for your data instead of using 'any'.

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

I encountered an issue while making customizations to my default next.config.js file. Despite attempting various solutions, I consistently encountered an error regarding the invalid src property

I'm currently trying to introduce some custom configurations into the next.config.js file. However, I keep encountering an error regarding an invalid src prop. Despite my attempts to troubleshoot in various ways, the error persists. // ...

"Changing the name of a symbol that is automatically imported from an internal library in

Within my module, I find myself using the Element class that is implicitly imported from the "dom" internal library. However, I also need to create my custom Element class within the same module. This presents a problem due to the name collision and poten ...

Is there a way to directly send an API Request from a Controller in Laravel 5.2?

I'm currently in the process of working on a project that involves API integration across multiple websites. While progressing, I realized that I've been relying heavily on AJAX requests using JQuery in my code (which can be viewed in the page s ...

Encountering a node-sass problem during npm installation in my Angular project on Mac OS

While attempting to install node_modules for my Angular project on Mac OS, I encountered an issue with node-sass. My Node.js version is v16.13.2 and the node-sass version in the project is ^4.14.1. The package.json files can be viewed in image1 and image2. ...

Is there a way to bypass the subscription confirmation?

One of the challenges I am facing involves a stream of data changes that is emitted: interface Data { id: number, prop: string } This stream is then altered by another stream that sends an HTTP request. At the end, I subscribe to the response: .subsc ...

Guidelines for simulating ActivatedRouteSnapshot in observable testing situations

I am currently testing an observable feature from a service in Angular. This particular observable will output a boolean value based on the queryParam provided. For effective testing of this observable, it is essential to mock the queryParam value. Howev ...

Resolving undefined in Ionic 4: Returning Data from Modal

I'm attempting to create a modal window that utilizes a radio group. When a user selects a value from the radio group, I want the modal to return the selected object. Here is the code for the radio group page and HTML: export class PopoverstationsPa ...

I am eager to perform DOM manipulation similar to jQuery but within the context of Angular 6

Is there a way to modify the background color of the main div when a button is clicked? <div> <p>I'd like to be able to change the background color of the parent div by clicking a certain button. </p> <button (click)=" ...

Anticipated outcome is the need to provide a value upon completion of arrow function recursion (consistent-return)

If I have a recursive function like the example provided, is it possible to simply return false after the recursive foo call? function foo(fn, redo, interval = 1000) { return new Promise( (resolve, reject) => { fn() .then(resolve) ...

React Navigation Browser

While developing my application, I encountered an error that I can't seem to resolve. It seems to be related to how I defined the routes in the code. Originally, the app had only one route, but after making changes to have multiple routes, I started g ...

Routing a second-level child in Angular2 directly to the root instead of the first child

I'm working on setting up a multi-level routing hierarchy for my app. It's structured like this: app |---core |---items Here is the router configuration and HTML code for my app: import { NgModule } from '@angular/core'; im ...

Combine various arrays of objects into one consolidated object

Problem: There are untyped objects returned with over 100 different possible keys. I aim to restructure all error objects, regardless of type, into a singular object. const data = [ { "type":"cat", "errors" ...

Adjust the size of each link in the highchart network diagram

Is it feasible to individually set the length of each link in a network graph using highcharts? I am interested in creating a visualization where each user is displayed at varying distances from the main center user. I have been experimenting with the lin ...

When working with Expo and React Native in TypeScript, VS code IntelliSense recommends using 'react-native/types' instead of just 'react-native'

My React Native TypeScript setup is showing react-native/types instead of react-native in IntelliSense. How can I fix this issue? I initialized my project using npx create-expo-app MyApp --template Typescript. Here is my tsconfig.json configuration. { ...

When working with Angular 5, the question arises: how and where to handle type conversion between form field values (typically strings) and model properties (such

As a newcomer to Angular, I am struggling with converting types between form field values (which are always strings) and typed model properties. In the following component, my goal is to double a number inputted by the user. The result will be displayed i ...

Unexpected behavior of ion-select: No rendering of selected value when applied to filtered data

I came across an unexpected issue with the dynamic data filtering feature of ion-select. In my application, users are required to choose three unique security questions during registration. I have an array of available questions: questions: Array<{isSe ...

Converting Antdesign's Datepicker to Typescript

I'm having trouble figuring out how to properly annotate the dateObj parameter in the handleDateChange function that I've created. App.tsx import { useState } from 'react'; import logo from './logo.svg'; ...

What is the best way to anticipate a formal announcement?

Hey there! I'm trying to set options for my Datatable and add a new field in my objects, but I need to await the completion of these dtOptions. How can I achieve this in the ngOnInit lifecycle hook? export class MyDashboardComponent implements OnInit ...

Conditional Return Types in a Typescript Function

There is a function that can return two different types, as shown below: function doSomething(obj: {a: string, b?: string}): string | number { if (obj.b) { return 'something' } return 1 } When the function is called with an object cont ...

Using Typescript for testing React components: successfully passing an array of objects as props

My current approach involves passing an array of objects to mock component data for testing: const mockPackage = { id: '1232-1234-12321-12321', name: 'Mock Package', price: 8.32, description: 'Mock description', glo ...