[json] How to convert an object to JSON correctly in Angular 2 with TypeScript

I'm creating an Angular 2 simple CRUD application that allows me to CRUD products. I'm trying to implement the post method so I can create a product. My backend is an ASP.NET Web API. I'm having some trouble because when transforming my Product object to JSON it is not doing it correctly. The expected JSON should be like this:

{
  "ID": 1,
  "Name": "Laptop",
  "Price": 2000
}

However, the JSON sent from my application is this:

{  
   "product":{  
      "Name":"Laptop",
      "Price":2000
   }
}

Why is it adding a "product" in the beginning of the JSON? What can I do to fix this? My code:

product.ts

export class Product {

    constructor(
        public ID: number,
        public Name: string,
        public Price: number
    ) { }   
}

product.service.ts

import {Injectable}   from '@angular/core';
import {Http, Response} from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Observable';

import {Product} from './product';

@Injectable()
export class ProductService {

    private productsUrl = 'http://localhost:58875/api/products';

    constructor(private http: Http) { }

    getProducts(): Observable<Product[]> {
        return this.http.get(this.productsUrl)
            .map((response: Response) => <Product[]>response.json())
            .catch(this.handleError);
    }

    addProduct(product: Product) {                
        let body = JSON.stringify({ product });            
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.productsUrl, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server Error');
    }
}

create-product.component.ts

import { Component, OnInit }  from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import { Product } from '../product'
import { ProductService } from '../product.service'

@Component({
    moduleId: module.id,
    selector: 'app-create-product',
    templateUrl: 'create-product.html',
    styleUrls: ['create-product.css'],
})
export class CreateProductComponent {

    product = new Product(undefined, '', undefined);
    errorMessage: string;

    constructor(private productService: ProductService) { }

    addProduct() {            
        if (!this.product) { return; }
        this.productService.addProduct(this.product)
            .subscribe(
            product => this.product,
            error => this.errorMessage = <any>error);
    }
}

create-product.html

<div class="container">
    <h1>Create Product</h1>
    <form (ngSubmit)="addProduct()">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" required [(ngModel)]="product.Name" name="Name"  #name="ngModel">
        </div>
        <div class="form-group">
            <label for="Price">Price</label>
            <input type="text" class="form-control" required [(ngModel)]="product.Price" name="Price">
        </div>
        <button type="submit" class="btn btn-default" (click)="addProduct">Add Product</button>
    </form>
</div>

This question is related to json post typescript angular

The answer is


If you are solely interested in outputting the JSON somewhere in your HTML, you could also use a pipe inside an interpolation. For example:

<p> {{ product | json }} </p>

I am not entirely sure it works for every AngularJS version, but it works perfectly in my Ionic App (which uses Angular 2+).


Tested and working in Angular 9.0

If you're getting the data using API

array: [];

ngOnInit()    {
this.service.method()
.subscribe(
    data=>
  {
    this.array = JSON.parse(JSON.stringify(data.object));
  }
)

}

You can use that array to print your results from API data in html template.

Like

<p>{{array['something']}}</p>

Because you're encapsulating the product again. Try to convert it like so:

let body = JSON.stringify(product); 

You'll have to parse again if you want it in actual JSON:

JSON.parse(JSON.stringify(object))

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7