d3.js angular2中的线图从url(服务器)获取数据而不是本地数据

时间:2017-04-02 06:58:37

标签: angular d3.js

我在d3 v4线图中遇到了困难,因为我想在角度2中使用来自服务器的一些虚拟数据绘制线图。 我从这个链接https://bl.ocks.org/mbostock/3883245获得了帮助。 我是angular2和d3的新手。请帮助,您的帮助将不胜感激。 有人在plunker上做,但它必须从url(服务器),没有本地数据和angular2中获取数据。

有人可以帮忙吗?

 Data in Url:-
    --------------
[{"title":"A","value":123},{"title":"B","value":445},{"title":"C","value":666},{"title":"D","value":123},{"title":"E","value":876},{"title":"F","value":234},{"title":"G","value":567},{"title":"H","value":987},{"title":"I","value":357},{"title":"J","value":865},{"title":"K","value":245},{"title":"L","value":999},{"title":"M","value":111},{"title":"N","value":222},{"title":"O","value":333},{"title":"P","value":444},{"title":"Q","value":555},{"title":"R","value":666},{"title":"S","value":777},{"title":"T","value":888},{"title":"U","value":999},{"title":"V","value":232},{"title":"X","value":757},{"title":"Y","value":234},{"title":"Z","value":876}]

LineChartdata-service.ts  
    ---------------------------------                                                                                                
    import { Injectable } from '@angular/core';
    import { Http, Response } from '@angular/http';                                              

    @Injectable()
    export class LineChartDataService {
    constructor(private http: Http) { }  
     getRemotedata(){                                                                                
    return this.http.get('http://-------:8088/restfullDataApi/jsondata')
   .map((response:Response) => response.json());
    }                                                                                                                                                                   

    LineChartComponent.ts  
    -------------------------------                                                        
    import { Component, OnInit} from '@angular/core';
    import { LineChartDataService } from './------';  
    import * as d3 from "d3";                 

    @Component({
     selector: 'app-line-chart',
     templateUrl: './line-chart.component.html',
        styleUrls: ['./line-chart.component.css']
      })               
    export class LineChartComponent implements OnInit {                                                
     private data: any;
     private jsondata: any;
     private margin = {top: 20, right: 20, bottom: 30, left: 50};
     private y: any;
      private  x: any;
    private svg:any;
    private width: any;
      private height: any;
    private margin:any;
    private g:any;
      private line: d3.Line<[number, number]>;

    constructor(private LinechartService: LineChartDataService) {
        this.width = 900 - this.margin.left - this.margin.right ;
        this.height = 500 - this.margin.top - this.margin.bottom;  
      }        
     ngOnInit() { 
    this.LinechartService.getRemotedata()
          .subscribe(
            success => this.drawLineChart(success),
            error => this.jsonData = error
          );} 

      private drawLineChart(jsonData) {
        console.log("Json Remote Data :: ");
        console.log(JSON.stringify(jsonData));
        //this.Data = jsonData; 

    this.svg = d3.select("svg"),
        this.margin = {top: 20, right: 20, bottom: 30, left: 50},
          this.g = this.svg.append("g").attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");

      this.x = d3.scaleLinear()
        .rangeRound([0, this.width]);

    this.y = d3.scaleLinear()
        .rangeRound([this.height, 0]);

    let line = d3.line()
        .x(function(d) { return x(d.title); })
        .y(function(d) { return y(d.value); });

    this.x.domain(d3.extent(this.jsondata, function (d) { return d.title; }));
      this.y.domain(d3.extent(this.jsondata, function (d) { return d.value; }));

      this.g.append("g")
        .attr("transform", "translate(0," + this.height + ")")
        .call(d3.axisBottom(this.x))
        .select(".domain")
          .remove();

      this.g.append("g")
        .call(d3.axisLeft(this.y))
        .append("text")
          .attr("fill", "#000")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", "0.71em")
          .attr("text-anchor", "end")
          .text("value");

      this.g.append("path")
       .datum(this.jsondata)
          .attr("fill", "none")
          .attr("stroke", "steelblue")
          .attr("stroke-linejoin", "round")
          .attr("stroke-linecap", "round")
          .attr("stroke-width", 1.5)
        .attr("d", this.line);  

    }}

1 个答案:

答案 0 :(得分:0)

我找到了答案,但效果很好。 如果有什么不对,需要一些建议。

    line-chart.component.ts
   ------------------------
            import { Component, ElementRef, AfterViewInit } from '@angular/core';
            import { LineChartData  } from '../../providers/linechart-data';
            import * as d3 from "d3";

            @Component({
              selector: 'app-line-chart',
              templateUrl: './line-chart.component.html',
              styleUrls: ['./line-chart.component.css']
            })
            export class LineChartComponent implements AfterViewInit {

              title: string = 'd3.js with Angular 2!';
              subtitle: string = 'Line Chart';
              host;
              path;
               private xAxis :any;;
              private yAxis :any;
                data: any;
             private xScale :any;
              private yScale :any;
              private margin = {top: 20, right: 20, bottom: 30, left: 50};
              private width: number;
              private height: number;
              private svg: any;
              private line: any;

              constructor(private LinechartService: PieChartData,private element: ElementRef) {
                this.width = 900 - this.margin.left - this.margin.right ;
                this.height = 500 - this.margin.top - this.margin.bottom;
              this.xScale = d3.scaleBand().range([0,this.width]); 
                this.yScale = d3.scaleLinear().range([this.height, 0]).domain([123,999]);
              }

              ngAfterViewInit(): void {
                this.getGlobalData();
              }
               getGlobalData() {
                 console.log("getglobaldata method");
                this.LinechartService.getGlobalData()
                .subscribe(
                   success => this.buildSVG(success),
                    error => this.data = error
                  );
                this.host = d3.select(this.element.nativeElement);
              }


             private buildSVG(data) {
                  console.log('In setMap(mapData), mapData getting assigned');
                this.data = data;
                console.log('mapData assigned as '+JSON.stringify(this.data));

                console.log('In buildSVG()');
                this.xAxis = d3.axisBottom(this.xScale)            
                this.yAxis = d3.axisLeft(this.yScale)

                this.host.html('');
                let self = this;

                // let area = d3.area()
                let line = d3.line()
                .curve(d3.curveBasis)
                 .x(function(d: any) { return self.xScale(d.title); })
                   .y(function(d: any) { return self.yScale(d.value); });

                this.svg = this.host.append('svg')
                  .attr('width', this.width + this.margin.left + this.margin.right)
                  .attr('height', this.height + this.margin.top + this.margin.bottom)
                  .append('g')
                  .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');


                  self.xScale.domain(d3.extent(self.data, function(d: any) { console.log("title:::"+d.title);return 0; }));
                  self.yScale.domain([0,d3.max(self.data, function(d: any) {console.log("value::::" +d.value); return 0; })]); 
                  self.xScale.domain(self.data.map(function(d: any) { return d.title }));                           
                  self.yScale.domain([0,d3.max(self.data, function(d: any) { return d.value; })]);
                  // this.area.yAxis0(this.yAxis(0));

                  self.svg.append('g')
                      .attr("class", "axis axis-x")
                      .attr('transform', 'translate(0,' + self.height + ')')
                      .call(self.xAxis)


                  self.svg.append('g')
                      .attr("class", "axis axis-y")
                      .call(self.yAxis)
                      .append('text')
                      .attr("class", "axis-title")
                      .attr('transform', 'rotate(-90)')
                      .attr('y', 6)
                      .attr('dy', '.71em')
                      .style('text-anchor', 'end')
                      .style("fill","black")
                      .text('Value()');

            //console.log(data)
                  self.svg.append('path')
                      .datum(data)
                      .attr("fill","none")
                  .attr("stroke", "steelblue")
                      .attr('class', 'line')
                      .attr('d', line);
                      // .attr('d', area);

            }
            }

            line-chart.component.css
            --------------------------
            .axis {
              font: 10px sans-serif;
            }

            .axis path,
            .axis line {
              fill: none;
              stroke: #000;
              /*shape-rendering: crispEdges;*/
            }

            .axis-title {
              fill: none;
              stroke: black;
              stroke-width: 0.5px;
            }




            .line {
              fill: none;
              stroke: steelblue;
              stroke-width: 1.5px;
            }

            linechart-data.ts
            --------------------
            import { Injectable } from '@angular/core';
            import { Http, Response } from '@angular/http';
            import 'rxjs/add/operator/map';
            import { Observable } from "rxjs/Observable";

            @Injectable()
            export class LineChartData {
                // data : string;


                constructor(private http: Http) { 
            getGlobalData(): Observable<any> {
        return this.http.get('http://.........:8088/restfullDataApi/UserService/jsondata')
          .map(this.extractData)
        //   .catch(this.handleError);
      }
     private extractData(res: Response) {
        let body = res.json();
        return body; 
        }
                }