简体   繁体   中英

Angular 4 / Typescript JSON Formatting

I am developing an Angular 4 application which speaks to a REST API by getting and sending JSON requests.

When I am preparing JSON requests for posting I am doing a lot of manual work to build the JSON..

I AM SURE THERE MUST BE A BETTER WAY THAN THE BELOW using a library or typescript trick.. But haven't been able to find one and am looking for recommendations.

const addressJson = ' { \n ' + this.jsonFormatField('Address', serviceAddress.address) + ',' +
            this.jsonFormatField('Address2', serviceAddress.address2) + '\n,' +
            this.jsonFormatField('City', address3) + '\n,' +

Have you tried JSON.stringify ? It accepts a regular JavaScript object as input and produces a string containing the associated JSON for it.

Angular will serialise an object to JSON for you:

const address = {
    Address: serviceAddress.address,
    Address2: serviceAddress.address2,
    City: address3
};

http
  .post('/your/rest/endpoint', address)
  // subscribe() is still necessary when using post().
  .subscribe(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM