Sending information to a RESTapi using Angular 6

Hi there! I am just starting out with Angular 6 and I am encountering an issue while trying to post data to a web API. The error message I am getting is:

Error Message: "400 Bad Request: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)"

I would really appreciate it if someone could point out where I might be making a mistake. Thank you in advance.

Here is my service:

addIncidents(newIncidents: Incidents): Observable<Incidents> {
return this.http.post<Incidents>('api/v1/events', newIncidents, {
    headers: new HttpHeaders({
        'Content-Type' : 'application/json'
    })
});

And here is my component:

saveIncidents(formValues: any): void {
const newIncidents: Incidents = <Incidents>formValues;
console.log(newIncidents);
this.dataStorageService.addIncidents(newIncidents)
.subscribe(
  (data: Incidents) => console.log(data),
  (err: any) => console.log(err)
);
}

Here is the Incidents Model:

export interface Incidents {

Incident_Start_Time: string;
Title: string;
Description: string;
Ticket: string;
}

Finally, here is the HTML button:

 <button type="button" class="btn btn-primary" (click)="saveIncidents()">Submit</button>

Answer №1

When the click event occurs, the saveIncidents() method is called without any parameters. However, the saveIncidents() method expects a parameter to be passed as the body request. Since this parameter is undefined, the body of the request will be empty.

To rectify this issue, you should include a parameter in the (click) event, which should contain all the values from the form. You can achieve this by assigning a template variable to the form element:

<form #incidents="ngForm" ...>

Subsequently, you can pass this variable to the method like so:

(click)="saveIncidents(incidents)"

This may require some modifications to your current implementation.

Answer №2

The expected content-type is not JSON.

To resolve this issue, you can either remove the headers entirely or modify it to "text/plain".

headers: {'Content-Type': 'text/plain'}

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

What is the best way to loop through a formarray and assign its values to a different array in TypeScript?

Within my form, I have a FormArray with a string parameter called "Foo". In an attempt to access it, I wrote: let formArray = this.form.get("Foo") as FormArray; let formArrayValues: {Foo: string}[]; //this data will be incorporated into the TypeScript mod ...

What is the best way to retrieve app.state in a Remix project when running a Cypress test?

One way Cypress can expose an app's state to the test runner is by using the following approach in React: class MyComponent extends React.Component { constructor (props) { super(props) // only expose the app during E2E tests if (window.C ...

Tips for sending a timestamp as input to a stored procedure in TypeScript with the mssql module

Currently, I am utilizing the mssql npm package to communicate with SQL server. I have encountered a dilemma where the variable (which is of type TIMESTAMP in sql server) fetched from a stored procedure is returned as a byte array. Now, I need to pass this ...

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

Having trouble with the Angular 2 QuickStart setup on your Linux system?

Currently in the process of setting up the Angular 2 Quick Start Tutorial from scratch on a virtualbox Linux machine build. Followed all steps as outlined in the 5-minute quick start, however, encountering an error when running "npm start": /media/sf_test ...

What sets apart exporting a component from importing its module in another module?

When working with Angular, consider having both module A and module B. If I intend to utilize "A-component" within components of module B, what is the distinction between importing module A in Module B compared to including the "A-component" in the exports ...

Inquiring about the application of spread argument in TypeScript

Here is some code I'm working on: import _ from 'lodash'; function test(num1: number, num2: number) { console.log(num1, num2); } test(..._.take(_.shuffle([0, 1, 2]), 2)); I encountered a TS2556 error while using the TS playground and ...

Guide to creating a dynamically filled dropdown menu with Angular 6 HTML

An array of employees is assigned tests by Lead. When assigning tests, the selected employee is properly assigned. When populating back, Lead can see which test is assigned to which employee. The issue I am facing is that EmployeeID is populated correctly ...

In order to either pass a component variable as a parameter or set it as a global variable

Currently, I am in the process of restructuring my Angular2/Ionic2 code and seeking advice on the best practice for my specific situation. Within my component, I have declared a variable (this.questions) that I need to utilize in my service method. There ...

Problems with displaying primeng chart in Angular2

I'm facing an issue with my Angular2 application where I am trying to display a PrimeNG line chart (http://www.primefaces.org/primeng/#/chart/line). The problem is that despite no error messages or 404's, the grid is not rendering and there is ju ...

In Angular, when using multiple-selection mode in mat selection, the Error Value should always be in the form of

**Everything is working fine except for one error in the console. How can I remove this error? Can anyone please help me? Save, Edit, and searching are working perfectly fine. ** public campaignCategoryFormGroup$: FormGroup = this.fb.group({ // 'c ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Associate the generic operator <T> with a FunctionConstructor

In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON. Here is how it looks like: export function deserializeJSON<T>(JSONString: string, ty ...

Issue with tsconfig path alias not resolving when paths are outside of the baseUri

I've encountered an issue in my monorepo where the tsconfig doesn't resolve paths that are located above the current project directory. Here's an overview of my project structure: ── apps │ ├── sahl │ │ ├── index ...

What is the best way to clear a token from SessionStorage upon exiting an Angular application?

I need to clear my sessionStorage every time I exit my application. App Module: export class AppModule implements OnInit, OnDestroy{ constructor(private overlayService: OverlayService, private logger: LoggerService, private userService: UserService, pr ...

Angular 8's cutting-edge feature: the dynamic password validator

Hello, I have an API that returns an array object called passwordPolicy with the following properties: PasswordMinLength: 6 passwordMinLowerCase: 1 passwordMinNumber: 1 passwordMinSymbol: 0 passwordMinUpperCase: 1 The values of these properties can change ...

tips for preventing issues when the data array is empty

Here is the JSON data that I am dealing with: { "id": 43, "dataEvento": "2022-09-01T00:00:00.000+0000", "dataInvio": null, "idComunicazioneAssociata": null, "certificatoMedico" ...

Struggling to retrieve the header in Angular 6

When setting headers from an Express server written in NodeJS, I use the following code: app.use('/routes', function(req, res, next) { res.setHeader('test', 'test'); next(); ); The headers are successfully sent to th ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...