简体   繁体   English

如何将JSON中的模板字符串转换为angular?

[英]How to convert a template string in JSON in angular?

I have this code in my ty file:我的 ty 文件中有这段代码:

onSubmit(form: NgForm){
console.log('Executado')
let dados = `
  name: ${form.value.name},
  email: ${form.value.email},
  specialty: ${form.value.specialty},
  password:${form.value.password}

  `;
  this.http.post(`${ this.apiURL }/auth/register_lawyer`, dados)
        .subscribe(
          resultado => {
            console.log(resultado)
          },
          erro => {
            if(erro.status == 400) {
              console.log(erro);
            }
          }
        )
}

How can I convert the dados I receive in the form into JSON file?如何将表格中收到的 dados 转换为 JSON 文件? something like:就像是:

   dados ={
"name":"Andrew",
"email":"teste@hotmail.com",
"specialty":"developer,
"password":"1234"

}

I want to pass the dados in JSON form via Post to my API. But I searched and found nothing.我想把JSON表格里的dados邮寄到我的API。但是我搜索了一下,什么也没找到。 I tried to use JSON.stringfy but not worked.我尝试使用 JSON.stringfy 但没有用。

Your dados string is not valid JSON because it doesn't follow JSON formatting rules (eg all keys must be in double-quotes, all strings must be delimited, etc).您的dados字符串无效 JSON 因为它不遵循 JSON 格式规则(例如,所有键必须用双引号引起来,所有字符串都必须定界,等等)。 Don't use template-strings to create JSON data because you'll need to handle things like escaping strings and things like that.不要使用模板字符串来创建 JSON 数据,因为您需要处理 escaping 字符串之类的东西。

Change your code to create a DTO object first, then if you still want your dados template-string then create that separately.更改您的代码以首先创建一个 DTO object ,然后如果您仍然想要您的dados模板字符串,则单独创建它。 To avoid repetition you could use a function to generate the string by enumerating the properties of the DTO.为避免重复,您可以使用 function 通过枚举 DTO 的属性来生成字符串。

const dto = {
    name     : form.value.name,
    email    : form.value.email,
    specialty: form.value.specialty,
    password : form.value.password
};

const url = `${ this.apiURL }/auth/register_lawyer`;
this.http.post( url, dto )    // <-- Passing a JavaScript `object` will automatically be converted to JSON by Angular: https://angular.io/guide/http#making-a-post-request
    .subscribe( resultado => {
        console.log(resultado)
        },
        erro => {
            if(erro.status == 400) {
                console.log(erro);
            }
        }
    );

const dados = `
    name: ${dto.name},
    email: ${dto.email},
    specialty: ${dto.specialty},
    password:${dto.password}
`;

If you want to create lots of those dados strings ( which are not JSON ), perhaps for logging purposes?如果你想创建很多dados字符串(不是 JSON ),也许是为了记录目的? (honestly, no idea), do this: (老实说,不知道),这样做:

function createTextThatIsNotJson( obj ) {

    let text = "";
    for( const key in obj ) {
        if( text.length > 0 ) text += ",\r\n";
        text += "    " + key + ": " + obj[key];
    }
    return text;
}

const dados = createTextThatIsNotJson( dto );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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