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

AngularJS: Tips for bypassing filtering when inputting values outside of the range [1,2,3,4]

Is there a way to prevent filtering when entering certain numbers in the text box, like 0 or 5? <div ng-app=""> <input type="text" ng-model="search"> <div ng-repeat='val in [1,2, 3, 4] | filter:search'> {{val}} </div> ...

How do I delete an element from an array in a MongoDB database using Node.js?

When running this query in ROBO 3T, the code executes correctly. However, when attempting to run it in nodejs, the code is not functioning as expected. //schema model const mongoose = require('mongoose'); const imageSchema = mongoose.Schema({ ...

Error encountered while attempting to download PDF file (blob) using JavaScript

Recently, I have been utilizing a method to download PDF files from the server using Laravel 8 (API Sanctum) and Vue 3. In my Vue component, I have implemented a function that allows for file downloads. const onDownloadDocument = (id) => { ...

The designated apiUser.json file could not be located within the _http.get() function

It's puzzling why my URL isn't working in _http.get('app/api/apiUsers') for Angular version 4.0.0, when it functions correctly in Angular version 2.3.1. The code is identical in both Angular versions: import { Injectable } from ' ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...

Implementing mixin functions in vue.router routes with Vue.js

Is there a way to dynamically change the title of the window based on each route? I have included a meta: { title: ... } object in each child object within the routes: []. Here is an example: routes: [ { path: 'profile/:id', name: 'Prof ...

What is the best way to modify the styling of my CSS attributes?

I'm currently working with this CSS code: input:checked + .selectablelabel .check { visibility: hidden; } Now, I want to change the visibility property to "visible" using JavaScript. I attempted the following: $(document).on('click', & ...

Can the z-index property be applied to the cursor?

Is it possible to control the z-index of the cursor using CSS or Javascript? It seems unlikely, but it would be interesting if it were possible. Imagine having buttons on a webpage and wanting to overlay a semi-transparent image on top of them for a cool ...

Leveraging server-side data with jQuery

When my client side JQuery receives an array of JSON called crude, I intend to access and use it in the following way: script. jQuery(function ($) { var x = 0; alert(!{JSON.stringify(crude[x])}); ...

Generating pop-up upon loading with CSS3

I have searched through numerous threads and forums in the hopes of finding a solution, but I haven't been successful. My issue lies with triggering a popup on my website. I followed online tutorials to create a popup window, which I was able to do su ...

Hmm, seems like there's an issue with the touchable child - it must either be native or forward setNativeProps to

Currently enrolled in a ReactNative course on Coursera, I am facing an error in a 4-year-old course: "Touchable child must either be native or forward setNativeProps to a native component." I am unsure about this error and would greatly appreciate any hel ...

tips for incorporating async/await within a promise

I am looking to incorporate async/await within the promise.allSettled function in order to convert currency by fetching data from an API or database where the currency rates are stored. Specifically, I want to use await as shown here, but I am unsure abou ...

Searching through an array based on a specific string

Could someone lend a hand in getting this to function... The code snippet below is functioning const acco = [{FullyQualifiedName=(-) Imposto Unico, Id=109, sparse=true, AcctNum=3.1.2.01.03027}, {FullyQualifiedName=13º Salário, Id=114, sparse=true, AcctN ...

Injecting services into AngularJS controllers helps to provide the necessary dependencies

Greetings! Here is the code snippet for my service: angular.module('lucho1App').factory('ApiExample', ['$http', '$q', function($http, $q) { return { promiseToHaveData: function() { return $ht ...

The issue of Angular child components rendering before receiving parent data

My current challenge involves a parent component (app.component) making an http request, storing the result in this.stats and then passing it as a prop to the child component (progression.component). The issue arises when my child component tries to render ...

Why are UI changes delayed when using Angular2 Google Maps events?

I am working on an Angular2 application that integrates the Google Maps JS API. When loading Google Maps, I include the script like this: <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> To listen to events on ...

Having issues fetching data from the store with the latest version of Ngrx

I've been trying to integrate ngrx into my Angular project, but I'm facing a challenge with retrieving and displaying data. Despite various attempts based on online resources, I can't seem to fetch the data from the store even though the sta ...

What is the best way to create a moving line using EaselJS and TweenJS?

My objective is to animate a line from point A to point B using the Tween function. I am utilizing the EaselJS drawing library and TweenJS for animation. Can I achieve this by using the moveTo function to animate a straight line from point A to point B? ...

React is nowhere to be seen

index.js: import react from 'react'; import {render} from 'react-dom'; render( <h1>Hello World!</h1>, document.getElementById('root') ); package.json: { "name": "", "version": "1.0.0", "descriptio ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...