从Angular 2中的Chartist API获取数据

时间:2017-03-07 15:46:56

标签: javascript api angular promise observable

我正在尝试使用Chartist构建一个包含来自我的Node.js API的数据的图表。在Chartist的文档中,有一个像这样的异步数据的例子:

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

但是我使用Observable从API获取数据,而且我无法处理PromiseObservable ... 我尝试使用我调用API的数据resolve Promise Observable但是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); } } 没有返回任何内容。我不确定如何处理这个:s 这是我的Angular 2组件:

Promise

也许我应该使用Observable来调用我的API而不是{{1}},但我不知道如何解决我的问题......

任何帮助:)

1 个答案:

答案 0 :(得分:1)

试试这个:

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

你也可以试试这个:

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