What is the process for including an object in an http.post request?

My contact object needs to be included in the http.post method. I'm struggling with where exactly to pass this contact parameter. Can you provide guidance on how to modify my code accordingly and also share any relevant links related to the http.post API? Code:

createContacts(contact) {
    console.log('the contact inside subscribe function',contact);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/contacts',{headers : headers}).subscribe(res => {
      console.log('inside postmehtod of sub.function', res.json());//only objects

    });

  }

package.json

{
  "name": "contactlist",
  "version": "0.1.0",
  "description": "A sample Node.js app using Express 4",
  "engines": {
    "node": "5.9.1"
  },
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "devDependencies": {
    "mongoose": "^4.6.2",
    "body-parser": "^1.15.2",
    "cors": "^2.8.0",
    "del": "2.2.0",
    "express": "^4.14.0",
    "http": "0.0.0",
    "method-override": "^2.3.6",
    "morgan": "^1.7.0",
    "superlogin": "^0.6.1"
  }
}

Answer №1

Click here for the HTTP post API documentation

Here is the TypeScript syntax for making a post request using an API:

createContacts(contact) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.post('http://localhost:8080/contacts', contact, {headers : headers})
      .subscribe(res => {
         console.log('Received response from post method', res.json());//only objects
      })
  }

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

Service injection in Angular 4 module not functioning properly even though it was declared at the module level

Introducing my unique service named VenueAdminInceptionService import {Subject} from 'rxjs/Subject'; import {Observable} from "rxjs/Observable"; import {VenueAdminInceptionModel} from '../../models/venueadmininceptionmodel/venueadmin.incept ...

The extracted text from the window appears to be blank

When attempting to enclose a selected string between two characters, I am encountering an issue. For example, when selecting 'test' and clicking on the change button, the selected text should change to 'atestb'. However, although I am a ...

different ways to retrieve component properties without using inheritance

In order to modify certain properties of components after login, such as the "message" property of HomeComponent and the "age" property of UserComponent, I am unable to inherit the component class. What are some alternative methods to achieve this? Authen ...

Building a user interface in Angular2 that consists of multiple components and utilizes

What is the recommended structure for an Angular2 (beta3) application with routing when incorporating a parent/child multi-component setup? When dealing with individual tables, I have set up the following structure: https://i.stack.imgur.com/BYqGU.jpg I ...

What is a way to incorporate two ngClass directives within a single div element?

Is it possible to include two ng-class directives within a single div element? If so, how should we go about writing them together? Thank you for your help. <div [ngClass]={'white-background': policyNumber.length <= 0} [ngClass]="getS ...

Creating routes with dynamic components or importing dynamic components in Angular 2 is a versatile and powerful feature

Is there a way to dynamically create routes or import components based on data? For instance, suppose I have a JSON file with objects containing RouteNames, paths, and ComponentNames. How can I dynamically generate route definitions from this data? The ch ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Performing a series of get requests in Angular 2

There is a configuration service that retrieves specific information from a JSON file. getConfiguration(key) { return this.http.get('./app/config/development.json').map(res => { this.result = res.json(); return this.result[ke ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

When using TypeScript, my sorting function returns a value of 0 for all time values

I have been trying to sort this JSON data by date using the provided code, but it does not seem to work as expected. Below is a snippet of my JSON: { "StatusCode":0, "StatusMessage":"OK", "StatusDescription":[ { "id":"1", ...

Steps for automatically incrementing a number when adding an item to an array using Angular

I am currently working on adding values to an array and displaying them in the view. Everything is functioning correctly, but I would like to include an auto-incrementing number with each item. The initial array is stored in a data.json file. [ {"i ...

Converting JSON objects into TypeScript classes: A step-by-step guide

My challenge lies in converting Django responses into Angular's User array. This conversion is necessary due to variations in variable names (first_name vs firstName) and implementing specific logic within the Angular User constructor. In simple term ...

Experimenting with NGXS selectors: A comprehensive guide

Hey there, I am currently utilizing the NGXS state management library in my application. I have a selector set up like this and everything seems to be functioning correctly. However, while testing the app, I encountered the following error message: "PrintI ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...

Guide to retrieving an array of arrays in Angular 2

How do I retrieve an array of array data in Angular 2? The JSON data I have is as shown below, [[{ "pk_emp_id":5, "tenant_id":"Zone1", "location_id":1, "emp_number":"sk44", "prefix":"", "first_name":"qqqqq", "middle_name":"www", "last_nam ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

Unlocking the Secrets of Passing ID Parameters Between Pages and Fetching Data from External APIs in Ionic 4

Before I get into it, apologies for the basic question, but I'm struggling to figure this out. Here's my issue: I have a list of categories that are being fetched from a nodeJS api. My goal is to fetch the subcategories based on the id from the d ...

What steps should I take to resolve the npm run build error in my Angular application when deploying it with a server in Visual Studio Code?

When attempting to build my application using the npm run build --configuration production command, I encountered the following errors that I am unsure how to address. Being new to utilizing npm build commands, I seek assistance in resolving this issue. n ...