如何使用 TypeScript 在 Angular 2 中正确地将对象转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38372134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:30:24  来源:igfitidea点击:

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

jsonposttypescriptangular

提问by Jo?o Paiva

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:

我正在创建一个 Angular 2 简单的 CRUD 应用程序,它允许我使用 CRUD 产品。我正在尝试实现 post 方法,以便我可以创建一个产品。我的后端是一个 ASP.NET Web API。我遇到了一些麻烦,因为在将我的 Product 对象转换为 JSON 时,它没有正确执行。预期的 JSON 应该是这样的:

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

However, the JSON sent from my application is this:

但是,从我的应用程序发送的 JSON 是这样的:

{  
   "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:

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

product.ts

产品.ts

export class Product {

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

product.service.ts

产品.服务.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

创建-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

创建-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>

回答by Akshay Rao

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

在您的 product.service.ts 中,您以错误的方式使用 stringify 方法..

Just use

只需使用

JSON.stringify(product) 

instead of

代替

JSON.stringify({product})

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

我已经检查过你的问题,在这之后它工作得很好。

回答by Oded Breiner

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

如果你想在实际的 JSON 中解析它,你将不得不再次解析:

JSON.parse(JSON.stringify(object))

回答by malvadao

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

如果您只对在 HTML 中的某处输出 JSON 感兴趣,您还可以在插值中使用管道。例如:

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

我不完全确定它适用于每个 AngularJS 版本,但它在我的 Ionic 应用程序(使用 Angular 2+)中完美运行。

回答by rinukkusu

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

因为你又在封装产品了。尝试像这样转换它:

let body = JSON.stringify(product); 

回答by Yogesh Chauhan

Tested and working in Angular 9.0

在 Angular 9.0 中测试和工作

If you're getting the data using API

如果您使用 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.

您可以使用该数组从 html 模板中的 API 数据打印结果。

Like

喜欢

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