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

心不动则不痛 提交于 2020-01-10 06:52:27

问题


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>

回答1:


In your product.service.ts you are using stringify method in a wrong way..

Just use

JSON.stringify(product) 

instead of

JSON.stringify({product})

i have checked your problem and after this it's working absolutely fine.




回答2:


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

JSON.parse(JSON.stringify(object))



回答3:


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+).




回答4:


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

let body = JSON.stringify(product); 


来源:https://stackoverflow.com/questions/38372134/how-to-convert-an-object-to-json-correctly-in-angular-2-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!