我在Angular 2中使用高图。如果我使用静态数据,图表会按预期呈现,但如果我在我的服务中使用来自http.get请求的数据并使用订阅将其转到我的组件中没有呈现。而返回的是空图表。我可以从console.log中看到数据按预期返回到组件。我不确定我做错了什么。以下是相关代码。先感谢您。
服务
const API_URL = 'https://api.blockchain.info/price/index-series?base=btc"e=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();
}
}