Search code examples
angularchart.jsangular5angular2-servicesfusioncharts

Angular 2: How to pass my API data to graph and Display the Graph with data


I'm new to Angular2/4/5, Thanks in advance

I have data from my API formated like this:

{
  "temp":49.47,
  "time":"05:17:55 PM"
}

Which I need to take the data from above format and pass the data into chart.js

I have a ServerService which is grabbing the data from my API

@Injectable()
export class ServerService {
    private basicUrl ='http://10.188.16.104:8001/ws/temp';
dataSource;

    constructor(private http: Http) { } 

  getServers(): Observable<any> {
    return this.http.get(this.basicUrl)
.subscribe(data =>this.dataSource =data);
    }
}

From my component code :

Updated code:

    export class DrawgraphComponent implements OnInit {
  id = 'chart1';
    width = 600;
    height = 400;
    type = 'line';
    dataFormat = 'json';
  dataSource;
  mydata; 
  dataSourceObservable :Observable<any> 
  constructor(private http: HttpClient,private service: ServerService) {      
    this.dataSourceObservable  = this.service.getServers()
  .map(response => response.json()).subscribe(
   (dataFromApi) => {
      this.mydata = {
        "chart": {
            "caption": "EASi's RTD-SIM",
            "subCaption": "Tempature vs Time",
            "numberprefix": "C",
            "theme": "fint"
         },
        "data": dataFromApi
       } 
   });


}

ngOnInit(): void {  }
}

and HTML code is

<div *ngIf=getGraphClicked>
            <fusioncharts
              [id]="id"
              [width]="width"
              [height]="height"
              [type]="type"
              [dataFormat]="dataFormat"
              [dataSource]="mydata">
            </fusioncharts>      
          </div>

Can any one help me out to plot a graph by using API data.


Solution

  • you can use async pipe

    dataSourceObservable :Observable<any>
    
    constructor(private serverService: ServerService) { 
     this.dataSourceObservable  = this.serverService.getServers()
      .map(response => response.json());  
    }
    
    ...
    
     <div *ngIf=getGraphClicked>
            <fusioncharts
              [id]="id"
              [width]="width"
              [height]="height"
              [type]="type"
              [dataFormat]="dataFormat"
              [dataSource]="dataSourceObservable | async">
            </fusioncharts>      
          </div>