错误TypeError:res [0] .price.map不是ChartJS中的函数

时间:2018-06-23 17:36:26

标签: javascript angular rest angular6

我正在尝试根据Rest数据绘制折线图,​​但出现此错误

  

core.js:1521错误TypeError:res [0] .price.map不是函数       在SafeSubscriber._next(app.component.ts:26)       在

这是代码

import { Component } from '@angular/core';
import { HelperService } from './helper.service';
import {Chart} from 'chart.js';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  chart = [];


  constructor(private _graph:HelperService){

  }

  ngOnInit(){


    this._graph.getGraphData()
        .subscribe(res => {
          console.log(res);

         let stock_price0 = res[0].price.map(res => res[0].price);
         let stock_price1 = res[1].price.map(res => res[1].price);

          let timeloop=[1,2,3,4,5,6];





         this.chart = new Chart('canvas',{
           type:'line',
           data: {
             labels:timeloop,
             datasets: [
               {
                 data:stock_price0,
                 borderColor:'#3cba9f',
                 fill:false
               },
               {
                data:stock_price1,
                borderColor:'#ffcc00',
                fill:false
              }
             ]
           },
           options:{
             legend:{
               display:false
             }
           }
         })

        })
  }
}

这是json格式,

  

[{“ id”:1,“ stockName”:“ A”,“ price”:5,“ qty”:10,“ sector”:“ Finance”},{“ id”:2,“ stockName” :“ B”,“价格”:3,“数量”:2,“部门”:“技术”},{“ id”:3,“股票名称”:“ C”,“价格”:4,“数量” :1,“ sector”:“ Gov”},{“ id”:4,“ stockName”:“ Z”,“ price”:2,“ qty”:5,“ sector”:“ Finance”},{“ id“:5,” stockName“:” J“,”价格“:5,” qty“:1,” sector“:” Gov“},{” id“:6,” stockName“:” K“,”价格”:3,“数量”:3,“部门”:“技术”}]

1 个答案:

答案 0 :(得分:0)

如果您查看JSON,则res [0] .price不是数组。它只是一个领域。地图在数组上工作。我认为您需要

  let stock_price0 = res[0].price;

编辑

我认为您需要将价格值放入数组中,

您可以这样做

 let stock_price0 = res[0].map(res => res.price);

演示

var myjson = [
  {
    "id": 1,
    "stockName": "A",
    "price": 5,
    "qty": 10,
    "sector": "Finance"
  },
  {
    "id": 2,
    "stockName": "B",
    "price": 3,
    "qty": 2,
    "sector": "Tech"
  },
  {
    "id": 3,
    "stockName": "C",
    "price": 4,
    "qty": 1,
    "sector": "Gov"
  },
  {
    "id": 4,
    "stockName": "Z",
    "price": 2,
    "qty": 5,
    "sector": "Finance"
  },
  {
    "id": 5,
    "stockName": "J",
    "price": 5,
    "qty": 1,
    "sector": "Gov"
  },
  {
    "id": 6,
    "stockName": "K",
    "price": 3,
    "qty": 3,
    "sector": "Tech"
  }
];
var result = myjson.map(a => a.price);
console.log(result);