Hugo
Hugo

Reputation: 163

Get data from an API for Chartist in Angular 2

I'm trying to build a chart with Chartist with data coming from my Node.js API. In the doc of Chartist there is an example of async data like this :

class AsyncChartComponent {
  data: Promise<Chartist.IChartistData>;
  type: Promise<ChartType>;

  constructor() {
    // simulate slow API call
    this.data = new Promise(function(resolve: any): void {
      setTimeout(function(): void {
        resolve(data['Pie']);
      }, 5000);
    });

    this.type = new Promise(function(resolve: any): void {
      setTimeout(function(): void {
        resolve('Pie');
      }, 5000);
    });
  }
}

But I get my data from API using Observable and I'm not able to deal with the Promise and the Observable... I try to resolve my Promise with the data from my call to the API but nothing is returned expect the Observable. I'm not sure how I have to deal with this :s Here is my Angular 2 component :

export class RatesComponent implements OnInit {
  @Output() changed = new EventEmitter<IRate>();

  rates: IRate[] = [];
  selectedRate: IRate;
  errorMessage: string;
  chart: Chart;
  chartData: Promise<Chartist.IChartistData>;
  type = 'Line';

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.getRates()
        .subscribe(
          (data: IRate[]) => {
            this.rates = data;
          },
          (error) => this.errorMessage = <any>error
        );

    this.chartData = new Promise((resolve: any): void => {
      resolve(this.dataService.getChartData());
    });

    this.dataService.getChartData()
        .subscribe(
          (data: Chartist.IChartistData) => {
            return data;
            // console.log(this.chartData);
          },
          (error) => this.errorMessage = <any>error
        );

    this.chart = {
      type: 'Line',
      data: JSONdata['Line2']
    };
  }

  select(rate: IRate) {
    this.selectedRate = rate;
    this.changed.emit(rate);
  }
}

Maybe that I should use Promise to call my API instead of Observable but I don't see how it would resolve my problem...

Any help :)

Upvotes: 0

Views: 715

Answers (1)

Adnan A.
Adnan A.

Reputation: 1982

Try this:

this.chartData = new Promise((resolve: any): void => {
   this.dataService.getChartData().subscribe((data: Chartist.IChartistData) => {
     resolve(data);
   },
     (error) => this.errorMessage = <any>error;
   );
});

You can also try this:

this.chartData = this.dataService.getChartData().toPromise();

Upvotes: 1

Related Questions