Trouble encountered when attempting to post an object using Angular 2 with typescript

When using Postman, the correct response is received with the following JSON in the body:

{
    "cpu": {
        "filters": [
            ]
    }
}

However, when I make a POST request in my Angular 2 service, the response seems to be empty. Here is the service code:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { BaseService } from './base.service';
import { Observable } from 'rxjs/Observable';
import { Cpu } from '../entities/cpu';
import { PostObject } from '../entities/post-object';
import { CPU } from '../datasource/database-data';
import 'rxjs/add/operator/map';

@Injectable()
export class CpuService extends BaseService {
    postObject: PostObject;

    constructor(private http: Http) {
      super();
    }

        getCpus(): void {
        this.postObject = new PostObject();
        console.log(JSON.stringify(this.postObject));
            this.http.post(this.getUrl('/searchCPU'), JSON.stringify(this.postObject))
                .subscribe((result: any) =>
                    console.log(result);
                    return result
                });
        }
}`

The structure of the PostObject class is as follows:

export class PostObject {
    cpu: {
        filters: string[]
    }
}

Oddly enough, when logging the postObject object, it appears to be empty. Could it be a problem with

this.postObject = new PostObject();
?

Answer №1

To send data, classes must have a constructor. It may seem odd to send an empty object, but you can also manually create an object without using classes. However, this method may not be ideal for maintenance purposes. Instead, you could achieve this by defining the object as follows:

this.postObject = {cpu:{filters:[]}} 

If you prefer using classes, you would need two separate classes:

export class PostObject {
    constructor(public cpu: Cpu) {}
}

export class Cpu {
    constructor(public filters: string[]) {}
}

You can then create a new PostObject instance like this:

this.postObject = new PostObject(new Cpu([]))

Both methods will result in the desired outcome:

{
    "cpu": {
        "filters": [
            ]
    }
}

Answer №2

To receive the JSON payload as the post body, ensure to specify the appropriate content-type header:

this.http.post(this.getUrl('/searchCPU'), JSON.stringify(this.dataObject), {headers:{'Content-Type': 'application/json'}})

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

Comparison of instancing, bufferGeometry, and interleavedBuffer in rendering techniques

I have a requirement to create numerous points and lines with position, size, and color attributes, and their positions are dynamic as they can be interactively dragged. Up until now, I have been using buffer Geometry, but recently I came across two other ...

Creating a dropdown button with three dots in a table row using jQuery

I've been working with tables and I'm trying to create a dropdown list with 3 dots in each table row. I've experimented with a few libraries and custom dropdown options, but none of them seem to be working properly. What I'm looking fo ...

Efficiently Trimming an Array of Strings in JavaScript based on specific String Matchingl

Imagine having an array like this: const arr = [ '0', 'parentNode', 'children', '0', 'values' ] The goal here is to trim the array until a specific string is found (excluding that string). For example, if ...

How can Node.js be used to link to a local file?

I'm having some trouble with a script source link that I've added: // index.html <script src="/js/jquery.js"></script> Even though the file exists, it doesn't seem to be working. I attempted to link to it in my Node.js server, ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

What is the most effective way to halt all AJAX processes on a webpage with jQuery?

Is there a way to use jQuery to halt all ongoing ajax processes on the page? ...

What is the process for retrieving an excel file from the backend to the frontend?

I am currently facing an issue where I want to initiate a browser download of an excel file that is generated in my backend. However, I am struggling to figure out how to pass this type of response. app.get('/all', function (req, res) { db.q ...

Utilizing Node JS to synchronously send HTTPS requests to two distinct links

My goal is to use Node JS to make HTTPS requests to an external link. Initially, I need to retrieve user ids by iterating through multiple users. Then, on subsequent calls, I will insert these user ids into the URL link to obtain user properties. This proc ...

React router-dom doesn't function properly when embedded in a nested organization

I am working on creating an authentication page with the following routes: /auth -> show auth status /auth/signin -> Sign in form /auth/signup -> Sign up form These are the components used in my App App.js function App() { return ( <Br ...

Leverage the power of Meteor by incorporating templates to dynamically inject HTML based on an event

I am currently generating HTML using JQuery on an event. However, I believe a better approach would be to use templates in Meteor, especially if the HTML becomes more complex. Template.example.onRendered(function() { paper.on({ 'cell:mous ...

Encountering difficulties in loading my personal components within angular2 framework

I encountered an issue while trying to load the component located at 'app/shared/lookup/lookup.component.ts' from 'app/associate/abc.component.ts' Folder Structure https://i.stack.imgur.com/sZwvK.jpg Error Message https://i.stack.img ...

Unable to create a pie chart with chartjs using JSON data

I am having trouble creating a pie chart using canvas.JS. I have already tried iterating through them in a loop. The JSON data returned looks like this: [[{"label":"belum","x":1},{"label":"sudah","x":5}]] Below is the code I am using to retrieve the JS ...

What is the process of converting a file into a binary stream using Javascript?

I'm currently in the process of building a website using Next.js and I want to upload a file to OneDrive using the Microsoft Graph REST API. The documentation states that the request body should be the binary stream of the file you wish to upload, bu ...

In Vue 3, what causes the dynamic class value to change along with the ref value when using a function with the ref property for binding?

I'm currently working on Vue code that looks like this. <template> <h1 :class="{ disabled: checkClass() }">Hello</h1> </template> <script setup lang="ts"> import { ref } from "vue"; const ...

A React component that dynamically increases the padding CSS value to render its children components

Greetings! I am working on a scenario where a React component needs to pass a padding value to styled components while incrementing it based on the nested rendering level. For example, imagine a List component that must display a parent and child component ...

What is the best way to hide the MatSlidePanel?

There is a side panel in my application that I need to close upon user action. I am facing an issue with the following error message: Property 'close' does not exist on type 'MatSlidePanel'.ts(2339) Below is the code snippet I attempte ...

Is there a way to determine if a server firewall such as mod_security is preventing jQuery Ajax connections?

If I encounter a scenario like this: https://i.sstatic.net/3JqI9.png How can I detect this situation using jQuery AJAX? The connection seems to hang without any HTTP Status Code, and there are no AJAX errors detected even though the file exists. I attem ...

Having issues with the $addToSet method in my MongoDB API implementation

Despite searching through various topics, I couldn't find a solution to my specific problem. In an effort to enhance my JavaScript skills, I embarked on creating a quote generator. I successfully developed the API and frontend components. However, c ...

Create a JavaScript function to implement a fade-in effect without relying on

Here is the code snippet that I am working with: document.getElementById('showRtb').addEventListener('click', function () { document.getElementById('rtb').style.display="inline-table"; }); document.getElementById(&ap ...

The animatedModal.js dialog box is causing the link to be unclickable, despite having a z-index of -9999

I am currently utilizing animatedModal.js for creating simple dialog boxes on my website. Everything is functioning perfectly, except for one issue - I am unable to click on the link to my logo at the top of the page because the modal with opacity:0; z-ind ...