2017-04-02 6 views
0

각도 2의 서버에서 더미 데이터를 사용하여 선형 차트를 그려야하므로 d3 v4 선형 차트에 어려움이 있습니다. 도움을 받았습니다. 이 링크 https://bl.ocks.org/mbostock/3883245. 나는 angular2와 d3을 처음 사용합니다. 제발 도와주세요, 당신의 도움을 주시면 감사하겠습니다. 누군가 plunker에서 수행하지만 url (서버), 로컬 데이터 및 angular2에서 데이터를 가져와야합니다.d3.js 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); 

    }} 
+0

코드를 게시 할 때 도움이 될 수 있습니다. – neuron

+0

LineChartdata-service.ts에는 어떤 항목이 있습니까? – neuron

+0

@Manz 스택 오버플로에 오신 것을 환영합니다. [질문하는 방법] (https://stackoverflow.com/help/how-to-ask)에 대한이 페이지를 읽어보십시오. 그 후 ** 대답 ** (대답이 아닙니다)을 삭제하고 질문에 코드를 게시하십시오. 질문 바로 아래에 "편집"이 있습니다. 클릭하여 코드를 붙여 넣으십시오. –

답변

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; 
     } 
       }