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

前端 未结 5 1100
灰色年华
灰色年华 2020-12-23 13:40

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.

相关标签:
5条回答
  • 2020-12-23 13:48

    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>
    
    0 讨论(0)
  • 2020-12-23 13:53

    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.

    0 讨论(0)
  • 2020-12-23 13:53

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

    let body = JSON.stringify(product); 
    
    0 讨论(0)
  • 2020-12-23 14:04

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

    0 讨论(0)
  • 2020-12-23 14:07

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

    JSON.parse(JSON.stringify(object))
    
    0 讨论(0)
提交回复
热议问题