【问题标题】:How to convert a template string in JSON in angular?如何以角度转换 JSON 中的模板字符串?
【发布时间】:2020-08-08 16:10:06
【问题描述】:

我的 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);
            }
          }
        )
}

如何将表单中收到的 dados 转换为 JSON 文件?类似:

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

}

我想通过 Post 将 JSON 格式的 dados 传递给我的 API。但我搜索并没有发现任何东西。我尝试使用 JSON.stringfy 但没有成功。

【问题讨论】:

  • 您的代码中有一个错误:问问自己,如果有人为 name 提交的值包含换行符、双引号或逗号,会发生什么?
  • JSON.stringify 应该够了,返回的错误是什么?
  • @AdMer JSON.stringify 不起作用,因为 dados 已经是一个字符串。 (见反引号),它不是object
  • @Dai 你是对的没看到

标签: javascript angular typescript template-strings


【解决方案1】:

您的 dados 字符串不是有效的 JSON,因为它不遵循 JSON 格式规则(例如,所有键都必须用双引号括起来,所有字符串都必须分隔,等等)。不要使用模板字符串来创建 JSON 数据,因为您需要处理转义字符串之类的事情。

首先更改您的代码以创建 DTO object,然后如果您仍然想要您的 dados 模板字符串,则单独创建它。为避免重复,您可以使用函数通过枚举 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}
`;

如果您想创建大量 dados 字符串(不是 JSON),也许是为了记录日志? (老实说,不知道),这样做:

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 );

【讨论】:

  • WOOOOOORKEEDDDD 谢谢
猜你喜欢
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多