在angular2中切换来自服务器的数据时获取错误

时间:2017-11-20 06:31:09

标签: angular

我在服务器下面有jsondata,我正在尝试slice the data下面的方法buildChart(jsonData),但是error为 - [{"B。 当数据采用以下格式时,jsonData未正确切片。

请帮助找出错误。

来自服务器的数据格式

// output- console.log('success:::' + JSON.stringify(success)) 

{"data":"[{\"Brand\":\"Lenovo\",\"Net Sales PRIOR\":\"1200598\",\"Net Sales\":\"1469476\",\"Net Sales CHANGE %\":\"22\"},{\"Brand\":\"Samsung\",\"Net Sales PRIOR\":\"1081820\",\"Net Sales\":\"1194071\",\"Net Sales CHANGE %\":\"10\"},{\"Brand\":\"Dell\",\"Net Sales PRIOR\":\"570745\",\"Net Sales\":\"1128782\",\"Net Sales CHANGE %\":\"97\"},{\"Brand\":\"Apple\",\"Net Sales PRIOR\":\"987349\",\"Net Sales\":\"997392\",\"Net Sales CHANGE %\":\"1\"},{\"Brand\":\"Acer\",\"Net Sales PRIOR\":\"810128\",\"Net Sales\":\"874786\",\"Net Sales CHANGE %\":\"7\"},{\"Brand\":\"Canon\",\"Net Sales PRIOR\":\"494803\",\"Net Sales\":\"677954\",\"Net Sales CHANGE %\":\"37\"},{\"Brand\":\"Sony\",\"Net Sales PRIOR\":\"548727\",\"Net Sales\":\"654016\",\"Net Sales CHANGE %\":\"19\"},{\"Brand\":\"HP\",\"Net Sales PRIOR\":\"409096\",\"Net Sales\":\"548593\",\"Net Sales CHANGE %\":\"34\"}]","meta":"","gtMap":"{}"}

app.component.ts

//上面的代码不是必需的,因此请从ngOnInit

开始关注主代码
ngOnInit(){
let thisx = this;
this.jsonDataService.getPIWSData(this.chartsAjaxMeta).subscribe(
          function (success) {
            thisx.data = success;
            console.log('success:::' + JSON.stringify(success));
            thisx.buildChart(success['data']);
          },
          error => 
            console.log('Getting Server Data Error :: ' + JSON.stringify(error));
});
buildChart(jsonData){
   console.log('jsonData::::' + jsonData)
  console.log('jsonData::::' + jsonData.slice(0, 10)); //<--- error as 
                                                //jsonData::::[{"B

}

1 个答案:

答案 0 :(得分:1)

首先尝试将此JSON.parse(jsonData)保存在变量

Node

然后

let temp=JSON.parse(jsonData);