从json拉出物体

时间:2017-03-01 18:58:44

标签: json http angular typescript

我有一个发送对象数组的API。每个对象包含2个数组(1个数字和1个字符串)和一个字符串。我成功地从API接收了一个JSON对象,我可以从我的http函数中将对象显示到我的控制台,并将其分配给var'聊天'。但是当我想在这个类代码的其他部分使用它时,我正在努力从标题var对象中获取数据。

例如,如果我尝试分配一个json儿童数组,例如someNewVar= this.title[0]我得到了

  输入字符串

无法访问

字符串

有人可以告诉我,例如我如何获得名为'标签'的字符串数组。出于我的目标?但是当我向控制台显示this.title [0]时,它说它是一个对象。

我的代码

import { Component } from '@angular/core';
import { HttpWebServiceService1 } from './http-web-service-service';
//Featureupdate: if data point is zero set to null as helps with y-axis range calc. How: create method to concatentate a string[] and run method against charts 2-7
//Feature update: rotate the graphes by populating a new chartDate array and rotating around each position
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [HttpWebServiceService1]
})
export class AppComponent {
  presscologo = 'logo.png';
    charts:string[];

  constructor(HttpWebServiceService1: HttpWebServiceService1){
    HttpWebServiceService1.getHTTP()
      .subscribe(
        resBody => this.charts = resBody.charts,
        error => console.error('Error: ' + error),
        () => console.log(this.charts[0])

      );
  }
}

我的JSON

{
    "charts": [{
        "title": "title 1",
        "labels": ["label1", "label2", "label3", "label4", "label5", "label6", "label7", "label8", "label9", "label10", "label11", "label12", "label13", "label14", "label15", "label16", "label17", "label18", "label19"],
        "dataObjects": [{
            "values": [3, 1, 1, "NULL", 2, 2, 3, 0, 0, 0, 1, 0, 2, 1, 0, 4, 2, 2, 0],
            "type": "bar"
        }]
    }, {
        "title": "title 2",
        "labels": ["label1", "label2", "label3", "label4", "label5", "label6", "label7", "label8", "label9", "label10", "label11", "label12", "label13", "label14", "label15", "label16", "label17", "label18", "label19"],
        "dataObjects": [{
            "values": [3, 1, 1, "NULL", 2, 2, 3, 0, 0, 0, 1, 0, 2, 1, 0, 4, 2, 2, 0],
            "type": "bar"
        }]
    }]
}

2 个答案:

答案 0 :(得分:0)

我还不能发表评论,所以我会把它写成答案,希望有所帮助。

您需要绑定从服务器获得的数据以及您在应用程序中使用的数据模型。

尝试创建此数据模型( chart.model.ts

class DataObject{
   values: number[];
   type: string;
}

export class Chart {
  title: string;
  labels: string[];
  dataObjects: DataObject[]
}

确保您从服务器收到图表数组Chart[])的响应,并且您的http服务中的getHTTP()应返回Observable<Chart[]>

现在您将图表声明为Chart [](charts: Chart[]

根据请求进行修改

图表服务( charts / charts.service.ts ):

import { Injectable } from '@angular/core';
import { Chart } from './charts/chart.model'
import { Observable} from 'rxjs/Rx';
import { Http, Response, Headers, RequestOptions } from '@angular/http';

// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ChartsService {
   // resolve HTTP using the constructor
   constructor (private http: Http) {}
   // example of url of charts
   private chartsUrl = 'http://localhost:9000/api/charts'; 

   // fetch all existing charts
   getCharts() : Observable<Chart[]> {
     // ...using get request
     return this.http.get(this.chartsUrl).map((res:Response) => res.json()).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
   }
}

应用组件:

import { Component , OnInit} from '@angular/core';
import { Chart } from './charts/chart.model'
import { ChartsService } from './charts/charts.service';
@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ChartsService]
})
export class AppComponent implements OnInit {
  presscologo = 'logo.png';
  charts:Chart[];

  constructor(private chartsService: ChartsService){}
  ngOnInit() {
     this.chartsService.getCharts()
        .subscribe(
            charts => {
                this.charts = charts; 
                console.log(this.charts);
            },
            error => console.error('Error: ' + error)
        );
  }
}

这应该有用!

答案 1 :(得分:0)

如果你只是从你的http电话中分配你的json:

服务:

getHTTP() {
  return this.http.get('url')
    .map(res => res.json())
}

你最终会得到一个Object,因为它返回的是一个对象。如果要提取对象数组,请从对象charts

中提取它
getHTTP() {
  return this.http.get('url')
    .map(res => res.json().charts)
}

然后你有一个对象数组,你可以轻松访问它们。

根据评论,您需要在subscribe内进行数据操作,因为这是异步操作,在外部执行,您很可能会因为没有值存在而导致应用程序抛出错误。所以像这样:

HttpWebServiceService1.getHTTP()
  .subscribe(data => {
     this.charts = data;
     // here do your manipulation!
     console.log(this.charts[0].title)
  });

希望这有帮助! :)