从订阅访问数据

时间:2017-01-24 22:35:37

标签: javascript json angular

我正在学习Angular 2并订阅了我的服务并返回了数据,但我现在需要for()在它到达视图之前循环它,所以我推了我的json进入一个已经是数组的数组,但不确定这是否正确。

基本上我想将我订阅的数据传递给我的控制器上的方法

public sublocation = [];
  private subscriptions = [];
  constructor(private statusService : StatusService) { 

  }  

  public getAllStatusList(){
    this.subscriptions.push(
      this.statusService.getStatusAPI()
      .subscribe(
        data => {
            this.sublocation.push(data);
        },
        error => console.log('Server Error'), 
      )
    );
  }

public getSublocation(){
    console.log(this.sublocation);
    //TRYING TO DO STUFF HERE like if sublocation == london
}

json示例

[
  [
    {
      "id": "19",
      "parentTag": "0",
      "name": "London",
      "deliveryType": "E",
      "enabled": "T",
      "outageTag": [],
      "sub": [
        {
          "id": "25",
          "parentTag": "19",
          "name": "London::Gatwick",
          "deliveryType": "E",
          "enabled": "T",
          "outageTag": []
        }
      ]
    }
  ]
]

服务

 export class StatusService {

  constructor(private http: Http) { 

  }

  public getStatusAPI(): Observable<any>{

    return this.http.get(environment.api)
      .map((response: Response) => this.getStatusList(response))
      .catch((error:any) => Observable.throw(error.json().error || 'Server Error'));
  }

  public getStatusList(responseData:any){
    let data = [];
    let res = responseData.json();
    for(let prop in res) {
      data.push(res[prop])
    }
    //console.log(data);
    return data;
  }

}

1 个答案:

答案 0 :(得分:0)

我假设您在问题中呈现的数据为JSON(不再是JSON),是您在循环并将其推送到数组后最终得到的数据。所以原始(和实际)JSON可能看起来像这样:

[
  {
    "id": "1",
    "parentTag": "0",
    "name": "London",
    "deliveryType": "E",
    "enabled": "T",
    "outageTag": [],
    "sub": [
      {
        "id": "25",
        "parentTag": "19",
        "name": "London::Gatwick",
        "deliveryType": "E",
        "enabled": "T",
        "outageTag": []
      }
    ]
  }
]

这意味着您不需要循环和推送到新阵列,您可以这样做:

return this.http.get(environment.api)
  .map(res => res.json())

在您的组件中订阅数据并执行您喜欢的任何操作。您在问题中提到要循环遍历数组并检查位置。所以做这样的事情:

this.statusService.getStatusAPI()
  .subscribe(d => {
    this.data = d;
    this.loopData();
  })

loopData() {
  // loop through array
  this.data.forEach(x => {
    // check name property of object
    if(x.name == 'London') {
      alert('An Object with name London found!');
    }
  });
}

使用此解决方案,您现在可以轻松访问对象数组中的数据,如上所述,循环遍历数组,然后引用对象属性,如x.namex.parentTag等......