我正在创建一个 Angular 2 简单的 CRUD 应用程序,它允许我对产品进行 CRUD。我正在尝试实现 post 方法,以便创建产品。我的后端是一个 ASP.NET Web API。我遇到了一些麻烦,因为将我的 Product 对象转换为 JSON 时它没有正确执行。预期的 JSON 应该是这样的:
{
"ID": 1,
"Name": "Laptop",
"Price": 2000
}
但是,从我的应用程序发送的 JSON 是这样的:
{
"product":{
"Name":"Laptop",
"Price":2000
}
}
为什么在 JSON 的开头添加“产品”?我能做些什么来解决这个问题?我的代码:
产品.ts
export class Product {
constructor(
public ID: number,
public Name: string,
public Price: number
) { }
}
产品.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');
}
}
创建-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);
}
}
创建-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>
原文由 João Paiva 发布,翻译遵循 CC BY-SA 4.0 许可协议
在您的 product.service.ts 中,您以错误的方式使用 stringify 方法..
只需使用
代替
我已经检查了您的问题,在此之后它工作得非常好。