【问题标题】:Reference .json file for external dataset in ng2-nvd3ng2-nvd3 中外部数据集的参考 .json 文件
【发布时间】:2016-05-09 20:20:20
【问题描述】:

我正在使用 ng2-nvd3,我想访问外部 json 数据。基于下面的代码 sn-p,我如何引用 .json 文件来保存与下面 this.data 数组中显示的数据相同的数据?

import {Component} from 'angular2/core';
declare let d3:any;
import {nvD3} from 'ng2-nvd3';

@Component({
  selector: 'bar-chart',
  directives: [nvD3],
  template: `
    <div>
      <nvd3 [options]="options" [data]="data"></nvd3>
    </div>
  `
})
export class BarChartComponent {
  options;
  data;

  ngOnInit() {
    this.options = {
      chart: {
        type: 'discreteBarChart',
        height: 450,
        margin: {
          top: 20,
          right: 20,
          bottom: 50,
          left: 55
        },
        x: function (d) {
          return d.label;
        },
        y: function (d) {
          return d.value;
        },
        showValues: true,
        valueFormat: function(d){
          return d3.format(',.4f')(d);
        },
        duration: 500,
        xAxis: {
          axisLabel: 'X axis',
        },
        yAxis: {
          axisLabel: 'Y axis',
          axisLabelDistance: -10
        }
      }
    }

    //Want to replace this with an external json file.
    this.data = [
      {
        key: "Cumulative Return",
        values: [
          {
            "label": "A",
            "value": -29.765957771107
          },
          {
            "label": "B",
            "value": 0
          },
          {
            "label": "C",
            "value": 32.807804682612
          },
          {
            "label": "D",
            "value": 196.45946739256
          },
          {
            "label": "E",
            "value": 0.19434030906893
          },
          {
            "label": "F",
            "value": -98.079782601442
          },
          {
            "label": "G",
            "value": -13.925743130903
          },
          {
            "label": "H",
            "value": -5.1387322875705
          }
        ]
      }
    ];
  }

}

【问题讨论】:

  • 你想在运行时使用 HTTP 加载文件,还是它总是静态的,你只想将它移动到另一个文件以保持这个组件小?
  • @James Stewart,如何在运行时使用 http 处理加载文件。这就是我想要的。

标签: json d3.js angular ng2-nvd3


【解决方案1】:

如果您只想将数据放在单独的文件中。

创建一个新文件:

your.data.service.ts

在那里:

export class YourDataService{


   public data: Array<any> = [
     {
       key: "Cumulative Return",
       values: [
         {
           "label": "A",
           "value": -29.765957771107
         }]
   }]

然后在组件中导入并引用它

import{YourDataService} from './your.data.service.ts'


public _data: Array<any>= YourDataService.data;

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
相关资源
最近更新 更多