访问 JSON 中的值 Angular 7

Access to a JSON Value in Angular 7

您好,我正在尝试从 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 文件[=15= 捕获它的响应]

 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我只需要邮件,因为我收到邮件后,网站需要向那个方向发送一封电子邮件

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 索引进行了硬编码,因为这可以回答您的问题。您可能会考虑一种更动态/更灵活的方式来获取您需要的地址或元素。