0

我在 Angular 2 中使用 highcharts。如果我使用静态数据,图表会按预期呈现,但如果我在我的服务中使用来自 http.get 请求的数据并使用订阅将其获取到我的组件,它不会呈现。相反,返回的是一个空图表。我可以从 console.log 看到数据按预期返回到组件。我不确定我做错了什么。下面是相关代码。先感谢您。

服务

const API_URL = 'https://api.blockchain.info/price/index-series?base=btc&quote=USD&start=1503145039&scale=7200';

@Injectable()
export class BitcoinPriceService {

loadstate: boolean;

stateChange: Subject<boolean> = new Subject<boolean>();

moneyArray = [];

moneyChange: Subject<any> = new Subject<any>();

private getArray(): void {
// this.moneyChange.next(this.moneyArray);
}

constructor(private http: Http) {
    this.loadstate = false;
}

private showLoader(): void {
  this.loadstate = true;
  this.stateChange.next(this.loadstate);
}

private hideLoader(): void {
  this.loadstate = false;
  this.stateChange.next(this.loadstate);
}

    getData(url = API_URL) {
    this.showLoader();
    return this.http.get(API_URL)
        .subscribe((res: Response) => {
            let results = this.moneyArray;
            let obj = res.json();
            obj.forEach(
                 function (o: any) {
                    results.push(o);
                }
            );
        })
// .error(err => {
        //   console.error('handling error within getData()', err);
        //   const fakeData = [{ name: 'no prices could be retrieved' }];
        //   return Observable.of(fakeData);
        // })
        // .finally(() => {
        //      this.getArray();
//        this.hideLoader();

//        console.log('hideloader', this.loadstate);
//        console.log(this.moneyArray);
//    });
} 

}

零件

export class ChartComponent implements OnInit {

priceData: Subscription;

loadstate: boolean;
subscription: Subscription;

moneyArray = [];

constructor(bs: BitcoinPriceService) {
    console.log(bs);
    this.priceData = bs.getData();
    this.loadstate = bs.loadstate
    this.subscription = bs.stateChange.subscribe((value) => { 
      this.loadstate = value; 
    });



    console.log('moneyArray', this.moneyArray = bs.moneyArray);

    console.log('priceData', this.priceData);
    console.log('loadstate', this.loadstate);
}


private data = [
    {
        name: 'USA',
        data: this.moneyArray
    }, 
    {
        name: 'USSR/Russia',
        data: this.moneyArray,
    }];

ngAfterViewInit() {
    this.renderChart();
}

renderChart(){
    jQuery('#container').highcharts({
        chart: {
            type: 'area'
        },
        title: {
            text: 'Bitcoin Price'
        },
        subtitle: {
            text: 'Source: thebulletin.metapress.com'
        },
        xAxis: {
            allowDecimals: false,
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                text: 'Nuclear weapon states'
            },
            labels: {
                formatter: function () {
                    return this.value / 1000 + 'k';
                }
            }
        },
        tooltip: {
            pointFormat: '{series.name} produced <b>{point.y:,.0f}</b>' +
                         '<br/>warheads in {point.x}'
        },
        plotOptions: {
            area: {
                pointStart: 1940,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            data: this.data,
            name: 'Value Type Description'
        }]
    });
}

ngOnDestroy() {
    //prevent memory leak when component destroyed
    this.subscription.unsubscribe();
}
}

这就是 JSON 数据返回到 moneyArray 的方式。 在此处输入图像描述

4

1 回答 1

0

我认为你应该使用'rxjs/add/operator/map';

import 'rxjs/add/operator/map';

constructor(bs: BitcoinPriceService, private zone: NgZone) {
  console.log(bs);
  this.priceData = bs.getData().map(resp => {
    //You can init your chart here
   };
  );
  this.loadstate = bs.loadstate
  this.subscription = bs.stateChange.subscribe((value) => { 
    this.loadstate = value; 
  });
}

此外,最好在单独的函数中编写 Api 调用并在 ngOnInit() 中调用它

于 2017-11-25T15:34:54.727 回答