Inadequate data being sent to the server from Angular2 post request

Currently, I have a form field whose value I am passing to a service as this.form.value. However, when I log this.form.value on the console, I see

Object { email: "zxzx", password: "zxzxx" }
. Despite this, when I send the same data to the service and make a call to the server with the following code:

import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Injectable} from 'angular2/core'
import {Post} from './post';
import {Observable} from 'rxjs/Observable';


@Injectable()
export class PostService {
private _url = "http://127.0.0.1/accounts/login_user/";
constructor(private _http:Http) {

}


createPost(post){

    return this._http.post(this._url,JSON.stringify(post))
    .map(res=>res.json());

}
}

The server is successfully getting called, but unfortunately, the values are not being passed through correctly. Upon logging the response on the console, I get the following result:

Object { _isScalar: false, source: Object, operator: Object }

If anyone could provide some guidance on how to resolve this issue, it would be greatly appreciated.

Thank you.

Answer №1

Your console.log is showing the observable related to your request, but not its actual result. To display the result, you can incorporate the do operator:

createPost(post){
  return this._http.post(this._url, JSON.stringify(post))
    .map(res=>res.json())
    .do(data => {
      console.log(data);
    });
}

You mentioned that the request is being executed. This will only happen if you subscribe to the observable:

this.service.createPost(...).subscribe(() => {
  (...)
});

Edit

Additionally, remember to specify the Content-Type header:

createPost(post){
  var headers = new Headers();
  headers.append('Content-Type', 'application/json');
  return this._http.post(this._url, JSON.stringify(post), { headers })
    .map(res=>res.json())
    .do(data => {
      console.log(data);
    });
}

Edit2

If you need to send an url-encoded form:

Make sure to include the Content-Type header:

createPost(post){
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

let content = new URLSearchParams();
content.set('prop', post.prop);
(...)

return this._http.post(this._url, content.toString(), { headers })
.map(res=>res.json())
.do(data => {
console.log(data);
});
}

Answer №2

If you don't subscribe(), the observable will not trigger any actions:

addNewPost(post){
  return this._http.post(this._url, JSON.stringify(post))
    .map(response => response.json())
    .do(value => console.log(value));
}

...
this.addNewPost(...).subscribe(result => console.log(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

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Issues with JQuery `.click()` event

Check out this snippet of code I'm working with: $(".item").click(function () { alert("clicked!"); }); I also have (hypothetically; in reality it's more complex) the following HTML on my page: <a href="#" class="item"> ...

Allow for the ability to choose a specific option for every individual line that is echoed in

I have researched several similar questions, but none of them address exactly what I am attempting to achieve. My goal is to use AJAX to fetch a PHP page that will display the contents of a folder on my server. Currently, the files are being listed line by ...

Unlocking the Power of ReactJS: Passing Values in Material UI for Advanced JSON Structures

How can I access complex objects in the GRID component of material UI? Specifically, I am trying to access the ami_info.account, but it only displays Undefined in the UI. var columns = [ { field: 'id', headerName: 'ID', width: 90, ...

Angular 9 is throwing an error that specifies that the options provided in the @ViewChild decorator must be in

After successfully upgrading my Angular project from version 8 to 9, I encountered an error when trying to run the project on localhost or build it. The error message states: ERROR in @ViewChild options must be an object literal The @ViewChild syntax that ...

Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct ...

How Angular can fetch data from a JSON file stored in an S3

I am attempting to retrieve data from a JSON file stored in an S3 bucket with public access. My goal is to parse this data and display it in an HTML table. http.get<Post>('https://jsonfile/file.json').subscribe (res => { cons ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

How to Use a For Each Loop with Google Maps DrawingManager to Create Polygons?

My Ionic 4 Application using Angular 8 incorporates a google maps component where I need to draw and edit multiple polygons, eventually saving their vertices in a database. Hard coding some polygons is easy with getPath() or getPaths(), but I'm utiliz ...

I possess a table that showcases MatIcon buttons. Upon clicking on a button, two additional buttons should appear at the bottom of the table

I am working on a table that contains mat-icon-buttons. When the button is clicked, it should display 2 additional buttons at the end of the table. Upon clicking the first button, its color changes from primary to red, and I would like to add two more butt ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following: import multipleActionObject from page; it("should be able to perform multiple operations", () => { multipleActionObject.chooseIndex(4).setValue(10); } Inste ...

Tips on eliminating certain text from a hyperlink

I need assistance with removing the text  Title from my link while preserving the image. <tr id="group0"> <td colspan="100" nowrap="" class="ms-gb"> <a href="javascript:" onclick="javascript:ExpCollGroup('28-1_', ...

Access my web application to easily download Jira tickets in XML format with just a single click

In order to retrieve all tickets from Jira within a specific time period, I currently have to manually extract them by clicking on the extract button in XML format. Subsequently, I download this XML file onto my web application and save it into the databa ...

Is there a way to conceal the headers during an ajax request?

I'm currently exploring APIs using jQuery and Ajax. To set the header of Ajax, I typically use code similar to this: headers: { "My-First-Header":"first value", "My-Second-Header":"second value" }, I am working on a basic school project and ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Performing a request following a POST operation within Postman

Currently, I am using a Post method on a URL which is expected to be written into a database. What I would like to do is create an "if" statement within the test tab in Postman to check the status of the response and then run a query to confirm that the ...

What is the method for sending one URL as a parameter within another URL?

When I try to access the route /new/:url with a request like /new/https://www.google.com, the response is Cannot GET /new/https://www.google.com. What I actually want to receive is the string https://www.google.com. I came across an answer on URL compone ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...