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
}

但是,从我的应用程序发送的JSON如下所示:

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

为什么要在JSON的开头添加"产品"?我能做些什么来解决这个问题?我的代码:

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');
    }
}

创造产品.组成部分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>

推荐答案

在你的产品中.服务你用错了stringify方法..

只要用就行了

JSON.stringify(product) 

instead of

JSON.stringify({product})

我已经判断了你的问题,在这之后它工作得非常好.

Json相关问答推荐

从先前的REST调用创建动态JSON主体

如何使用PlayWriter循环访问JSON对象

在Reaction中从JSON文件中筛选数组

递归解码嵌套列表(具有任意深度的列表列表)

Oracle JSON 查询中的动态列列表

PostgreSQL:删除 JSONB 数组中每个元素的特定键

使用 jq,如何将两个属性构成键的对象数组转换为对象的索引对象?

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

传统编程语言等价于动态 SQL

Powershell 无法从名为 count 的键中获取价值

如何配置spring mvc 3在json响应中不返回null对象?

如何在 Eclipse 中安装和使用 JSON 编辑器?

以 unicode 将 pandas DataFrame 写入 JSON

Jackson Scala 模块的小例子?

在 JSON 对象中强制执行非空字段

我们可以使用 JSON 作为数据库吗?

通过 JSON 发送 HTML 代码

Django:TypeError:[] 不是 JSON 可序列化的为什么?

JSON JQ 如果没有 else

SCRIPT5009:JSON未定义