Unable to parse the JSON value as a boolean data type. Location: $

Seeking assistance with sending a request from an Angular frontend to an ASP.NET API server. The form for submission is defined as:

export class SaleToUpdate {
    id: number;
    shipped: boolean;
    shipDate: string;
    returned: boolean;
    returnDate: string;
}

Markup and Code

<mat-grid-tile [colspan] = "2" [rowspan] = "1">
        <mat-form-field>
            <input formControlName="shipDate" matInput placeholder="Ship Date">                                         
         </mat-form-field>                
         <div class="radio-group ml-3">
              <mat-radio-group formControlName="shipped" required (ngModelChange)="shipped">           
                    <mat-radio-button value="false">No</mat-radio-button>
                     <mat-radio-button value="true" class="ml-4">Yes</mat-radio-button>
              </mat-radio-group>
         </div>
</mat-grid-tile>  

The onSubmit() function

onSubmit() {    
   if (this.salesService.saleForm.valid) {
      let sale: SaleToUpdate = this.salesService.saleForm.value;  
      console.log(sale); 

      this.salesService.updateSale(sale.id, sale).subscribe(res => {
         console.log(res);
      }, error => {
        console.log(error);
      });
   } 
}

Therefore, my goal is to send the form data (SaleToUpdate class) to the backend server.

Data Transfer Object (DTO) on Server-Side

using System;
namespace API.Dtos
{
   public class SaleUpdateDto
   {      
       public int Id { get; set; }          
       public bool Shipped { get; set; }
       public DateTime ShipDate { get; set; }       
       public bool Returned { get; set; }
       public DateTime ReturnDate { get; set; }
   }
}

Encountering an error from the console:

"The JSON value could not be converted to System.Boolean. Path: $.shipped | LineNumber: 0 | BytePositionInLine: 274." when clicking onSubmit from the client.

Observation that the values for 'shipped' and 'returned' from the form are of type string, rather than boolean.

Any suggestions for resolving this issue would be greatly appreciated. Thank you!

Answer №1

Modify your boolean values coming from the Class

let saleData: SaleToUpdate = this.salesService.saleForm.value;

saleData.shipped = saleData.shipped === 'true' ? true : false;
saleData.returned = saleData.returned === 'true' ? true : false;

Answer №2

Before you submit the form, make sure to format the data correctly. You can achieve this by creating a new data object and converting the value from string to boolean. Here's an example:

onSubmit() {    
    if (this.salesService.saleForm.valid) {
      let sale: SaleToUpdate = this.salesService.saleForm.value;  
      console.log(sale); 
      //Here is where you should parse the object
      var data = {
            id: sale.id,
            shipDate: sale.shipDate,
            shipped: sale.shipped === 'true' ? true : false //This line handles the conversion
            ....
       }
      this.salesService.updateSale(sale.id, data).subscribe(res => {
        console.log(res);
      }, error => {
        console.log(error);
      });
    } 
  }

We hope you find this explanation helpful.

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 procedure for linking my SQL database with Angular?

This is a sample HTML code snippet to create a sign-in form: <div class="col-md-8"> <form (submit)="onSubmit()" method="POST"> <input type="text" class="form-control mb-2" name="names" [(ngModel)]="profileForm.name" placeholder="Usern ...

Cannot utilize a string as an index in an object due to the expression being of type 'string' - this results in an error

What is causing TypeScript to report this error? "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ '&': string; '"': string; "'&qu ...

Conversion of UTC timestamp to a timestamp in the specified timezone

this.selectedTimezone="Pacific/Kiritimati"; //this value will come from a dropdown menu These records represent the data.body returned by an API call. Iterating through each record in the dataset: { We are creating a new Date object based on the ...

Dealing with a multitude of parameters in the Angular 2/4 router: What you need to know

Within my application, the URL structure can vary with multiple parameters followed by an optional pattern. Here are some examples of possible URLs: http://example.com/{param1} http://example.com/{param1}/constant/{id} http://example.com/{param1}/{param ...

How can I compare just the keys, not the values, in a JSON object using JavaScript

I am dealing with two sets of nested JSON objects //First JSON object { "version": "1", "user": { "id": 123 } } //Second JSON object { "version": "1", "user": { "i": 123 } } 1) The comparison should focus on keys ...

What is the best way to exceed the capacity of a function in TypeScript by incorporating optional

I've been working on converting some code from JavaScript to TypeScript, and I have a specific requirement for the return type of a function. The function should return void if a callback parameter is provided, otherwise it should return Promise<o ...

What sets observable.throw apart from service.subscribe().error?

Can you explain the contrast? this.ApiService.getList().catch((e, c) => { return Observable.throw(e); }) .subscribe() => {} to this one this.ApiService.getList().subscribe(() => {}, error => {notifyService.showError(error._body); }) ...

Creating a new project in ASP Net Core Angular using Bootstrap 4 for the SideMenu layout instead of Bootstrap 3

I am currently working on developing a website using Angular6, where I aim to have a vertical navbar for large screens and a top navbar with dropdown functionality for mobile devices. While searching online, I came across several examples that seemed overl ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Storing arrays as JSON in PostgreSQL

Hey there, I'm struggling with a json array issue in postgresql. Here's the query that's causing me trouble: select array_to_json(array_agg(row_to_json(t))) from ( select id, ids, liv, tip, ide, idf nome, ico, rgb, ( select arr ...

Retrieve the initial array from the object that has a size of X

As part of my web app development process, I am utilizing the xlsx library to import data from an excel file. Each row from the excel sheet is being saved into an object that contains arrays with a length corresponding to the number of cells in each row. T ...

Jasmine was surprised when an error occurred while trying to create a spy object

I'm trying to simulate and meet the else condition for the method below, but I keep receiving an error stating Expected spy modalService.open not to have been called. Below is the code snippet of the component: After changing the line component.isEr ...

Create a nested object within an object in Angular 2

I am currently working with a model named "Professional" which includes a property that is another model called "Address": 'use strict'; import * as Address from './models/address'; export interface Professional { id?: number; ...

Encountering a "breaks the Content Security Policy directive: 'default-src 'none''" message while trying to deploy an Angular application on Heroku

I've been encountering difficulties while attempting to deploy my Angular app on Heroku. An error message keeps popping up stating that the image '' violates the Content Security Policy directive: "default-src 'none'". Even though ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

Adding items to a JSON list: A step-by-step guide

This question may seem familiar, but I have not been able to find a solution to my specific issue. In my case, I am working with a file named d.json which contains IDs and names, serving as a test file. { "id": [ "1", "2" ], "n ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

accessing an array variable within an HTML document

export class FirmsPage { langs; langForm; loading: any; username : string; firms; constructor(public navCtrl: NavController, private navParams: NavParams, public firmService: FirmService, public loadingCtrl: LoadingController) { this.user ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

Struggling to identify the memory leak in my Express.js Jest tests

Lately, I've been investing a considerable amount of time into identifying memory leaks within my Jest tests. While I have managed to resolve some issues, there is still a noticeable amount of memory leakage occurring from one test suite to the next. ...