Angular http获取数据并将json对象放入变量

时间:2018-10-12 02:32:43

标签: json angular angular-httpclient

我想获取officeid id,代码,名称,简称,accroym中的嵌套数据。并将其放入单个变量。

我该怎么做?

我的代码:

{
  "id": 1,
  "code": "1000-001-1-01-001-001",
  "name": "PEACE AND ORDER PROGRAM",
  "isActive": true,
  "majorFinalOutput": null,

  "officeId": 1,

"office": {
  "id": 1,
  "code": "1-01-001",
  "name": "Office of the Governor",
  "shortName": "PGO",
  "accronym": "PGO",
  "website": null,
  "email": null,
  "telephone": null,
  "fax": null,
  "type": "1"
},

 "sectorId": 1,

"sector": {
  "id": 1,
  "name": "General Public Services Sector",
  "code": "1000",
  "parentId": null,
  "parent": null
},

  "dateCreated": "2018-10-02T14:23:04.913",
  "dateModified": null,
  "createdBy": null,
  "modifiedBy": null
}

 getProgram() {
     return this.httpClient.get('api/programs/' + idhold).subscribe((holdprogram: any[]) => {
    console.log(holdprogram);
    });

  return this.programService.editProgram().finally( () => {

  }).subscribe((holdprogram: any[]) => {
    console.log(holdprogram);
    console.log(holdprogram.office.id);
    console.log(holdprogram.office.name);
    console.log(holdprogram.office.shortname);
  }, error => {
    console.error(error);
  },
  () => {
  });
}

1 个答案:

答案 0 :(得分:0)

保留对通过请求获得的变量的引用的最简单的通常方法是使用组件变量:

在组件中:

public export class MyComponent {
    ...
    public office: any; // instead of using 'any', you could create an interface corresponding to the structure

    ...
}

在订阅中:

.subscribe((holdprogram: any[]) => {
    this.office = holdprogram.office;
    console.log(this.office);
    // now this.office keeps a reference of your nested variable 'office'.
}, 

如果您需要在各个组件之间保留对它的引用,则它会更加复杂:您可以在服务级别上执行类似的操作(使用tap和局部变量),并且需要添加一些“缓存处理”机制。