【问题标题】:Access to a JSON Value in Angular 7在 Angular 7 中访问 JSON 值
【发布时间】:2019-09-27 03:57:58
【问题描述】:

您好,我正在尝试从 JSON 访问特定密钥。我正在使用 node.js 和 Angular 7 我得到的 JSON 是 stringfy,它来自一个 API。

这是我得到的 JSON

  "search": {
    "entry": [
      {
        "dn": "uid=080030781,c=mx,ou=s,o=i.com",
        "attribute": [
          { "name": "mail", "value": ["CAMILA.CAMPOS.TELLEZ@mail.com", "MX08@mail.com"] }]
      }
    ],
      "return": {
      "code": 0,
        "message": "Success",
          "count": 1
    }
  }
}

我需要访问键“value”,因为我需要获取值“camila.campos.tellez@mail.com”。 我从一个名为 app.js 的 node.js 文件中声明的 API 获取 JSON,然后我使用这个 service.ts 文件捕获它的响应

 getApproverMail(name) {
    console.log('entered to rootservice');
    return this.http.get(this.baseUrl + '/costing/operations?name=' + name);
  }

最后我可以通过带有此代码的 component.ts 文件访问它

findApproverMail() {

    this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
      this.email = res;
      console.log('Test: ' + res);
    });

  }

浏览器控制台会打印我向您展示的 JSON。但是我怎样才能只访问邮件的价值呢? P.D 我只需要邮件,因为收到邮件后,网站需要向该方向发送电子邮件

【问题讨论】:

    标签: node.js angular api angular7


    【解决方案1】:

    JSON 代表 JavaScript 对象表示法。任何有效的 JSON 都是 JavaScript(和 TypeScript)中的对象。您可以使用点符号导航到对象中:

    findApproverMail() {
    
        this.rootService.getApproverMail(this.aproverName).subscribe((res) => {
          this.email = res.search.entry[0].attribute[0].value[0];
          console.log('Test: ' + res);
        });
    
      }
    

    我建议按照您对服务的期望定义一个interface。它比仅仅围绕 any 类型的对象进行索引更干净。

    还请注意,我对 0 索引进行了硬编码,因为这回答了您的问题。您可能会考虑一种更动态/更灵活的方式来获取您需要的地址或元素。

    【讨论】:

    • 我试着按照你告诉我的去做,但我得到了这个错误:(“res.search.entry is undefined”
    • 嘿,非常感谢,我意识到我没有发送 Json 对象,我只发送了一个带有 Json 数据的字符串,这就是为什么我无法按照你告诉我的方式访问该对象.谢谢!
    • 为此您可以使用JSON.parse(jsonString)
    猜你喜欢
    • 2016-05-17
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    相关资源
    最近更新 更多