简体   繁体   English

检查返回的json对象是否有数据类型脚本和angular2

[英]checking return json object for data typescript and angular2

so i have made a call to check and see if i return an object with actual data in it - I am not sure if i am doing this wrong but this is what i am trying. 所以我打电话来检查是否返回了包含实际数据的对象-我不确定我是否做错了,但这就是我正在尝试的方法。

Here is my get call i have made to my services - COMPONENT FILE: 这是我对我的服务所拨打的电话-组件文件:

resultData: any = [];
barChartLabels: any =[];

getData(){
    this.dataService.getData().subscribe((data) => {
       this.resultData = data; 
       for(let item of this.resultData) { 
           this.barChartLabels.push(item.name);
       }
    }
}

I am currently seeing this.resultData in my console but know after pushing item's name into another array which is used in binding in my html it is not being displayed. 我目前在控制台中看到this.resultData ,但是知道将项目名称推送到另一个用于绑定html的数组中之后,它不会显示。

Here is my service call - SERVICE FILE: 这是我的服务电话-SERVICE FILE:

getData(){
        return this.http.get('my url')
            .map((res:Response) => res.json());
    }

Here is also what i have in my json file: 这也是我的json文件中的内容:

[
  {
    "id": 1,
    "name": "Test 1",
    "score": 34
  },
  {
    "id": 2,
    "name": "Test 2",
    "score": 92
  }
]

This is my html: 这是我的html:

<canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]="barChartType">

  </canvas>

This may have transitioned into a different topic now. 现在这可能已经转变为另一个主题。

If you really want it to be in the component, then the code needs to be in the body of the arrow function. 如果您确实希望将其包含在组件中,则代码需要位于arrow函数的主体中。 Something like this: 像这样:

getData(){
    this.dataService.getData().subscribe(data => {
       this.resultData = data;
       for(let resultItem of this.resultData){
         console.log(resultItem);
       }
    })
  }

This is because the subscribe is asynchronous. 这是因为订阅是异步的。 When the getData method first runs, this.resultData has no value. 首次运行getData方法时, this.resultData没有值。 It isn't until the Http response is returned that this.resultData is set. 直到返回Http响应,才设置this.resultData

You can use the do operator to see the data that is returned. 您可以使用do运算符查看返回的数据。 You could try something like this: 您可以尝试这样的事情:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

...

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM