Я пытаюсь реализовать этот компонент диаграммы https://www.highcharts.com/stock/demo/lazy-loading в моем приложении angular -cli. Диаграмма получает данные из веб-интерфейса. Позволяет указать новый диапазон дат. Когда вы это делаете, событие инициируется, и в этом случае вы можете вызвать службу веб-интерфейса и запросить новые данные.
Вы конфигурируете диаграмму, передавая некоторые параметры в конструкторе
this.chart = new StockChart(this.chartOptions);
Одна из опций, которую вы можете установить, - это событие, которое срабатывает при выборе нового диапазона дат
this.chartOptions = {
...
xAxis: {
events: {
afterSetExtremes: this.afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},
...
}
Поэтому, когда вы выбираете новый диапазон дат, эта функция вызывается
afterSetExtremes(e: { min: number; max: number }) {
console.log('Here we should load data. min: ' + e.min + ' max: ' + e.max);
}
Именно в этой функции мои проблемы заключаются в том, что «this» разрешается в элементе управления диаграммой, а не в моем компоненте, поэтому я не могу получить доступ к свойству WebApi Service, httpclient или другим методам, свойству в моем компоненте.
Если Я внутри функции afterSetExtremes делаю
console.log(this);
я получаю диаграмму, а не компонент, как я ожидал
если я console.log (this) из моего конструктора, я получаю ожидаемое значение, мой компонент и доступ к моей службе API
constructor(private apiService: ApiService, private activateRoute: ActivatedRoute) {
...
console.log(this);
}
* * Все это приводит к тому, что я не могу Воспользуйтесь моим сервисом и получите обновленные данные, так как я не могу сослаться на мой apiservice и / или мою функцию getChartData **
Вот полный код для моего компонента
import { Component, OnInit } from '@angular/core';
import { StockChart } from 'angular-highcharts';
import { ApiService } from '@app/services/snakeApi/api.service';
import { ActivatedRoute } from '@angular/router';
import { finalize } from 'rxjs/operators';
import { ChartDataCandleStick, ChartDataIndicator } from '@app/model/ChartData';
import { Options } from 'highcharts/highstock';
@Component({
selector: 'app-candlestick-and-volume',
templateUrl: './candlestick-and-volume.component.html',
styleUrls: ['./candlestick-and-volume.component.scss']
})
export class CandlestickAndVolumeComponent implements OnInit {
chart: StockChart;
chartDataCandleStick: Array<ChartDataCandleStick> = new Array<ChartDataCandleStick>();
chartDataIndicatorUpper: Array<ChartDataIndicator> = new Array<ChartDataIndicator>();
chartDataIndicatorLower: Array<ChartDataIndicator> = new Array<ChartDataIndicator>();
sub: any;
correlationId: string;
chartOptions: Options;
candleStickDataArray: any = [];
volumeDataArray: any = [];
indicatorUpperDataArray: any = [];
indicatorLowerDataArray: any = [];
constructor(private apiService: ApiService, private activateRoute: ActivatedRoute) {
this.sub = this.activateRoute.params.subscribe(params => {
this.correlationId = params.correlationId;
this.getChartData(-1, -1);
console.log(this);
});
}
getChartData(min: number, max: number) {
this.apiService
.getChartData({ correlationId: this.correlationId, startdateAsUnixTimeStamp: min, enddateAsUnixTimeStamp: max })
.pipe(
finalize(() => {
if (this.chartDataCandleStick.length > 0) {
this.updateChart();
}
})
)
.subscribe(response => {
this.chartDataCandleStick = response.ChartDataCandleStick;
this.chartDataIndicatorUpper = response.ChartDataIndicatorUpper;
this.chartDataIndicatorLower = response.ChartDataIndicatorLower;
});
}
updateChart() {
const candleStickDataLength = this.chartDataCandleStick.length;
const indicatorUpperDataLength = this.chartDataIndicatorUpper.length;
const indicatorLowerDataLength = this.chartDataIndicatorLower.length;
// set the allowed units for data grouping
let groupingUnits = [],
i = 0;
for (i; i < candleStickDataLength; i += 1) {
this.candleStickDataArray.push([
this.chartDataCandleStick[i].Date, // the date
this.chartDataCandleStick[i].Open, // open
this.chartDataCandleStick[i].High, // high
this.chartDataCandleStick[i].Low, // low
this.chartDataCandleStick[i].Close // close
]);
this.volumeDataArray.push([
this.chartDataCandleStick[i].Date, // the date
this.chartDataCandleStick[i].Volume // the volume
]);
}
for (i; i < indicatorUpperDataLength; i += 1) {
this.indicatorUpperDataArray.push([
this.chartDataIndicatorUpper[i].Date, // the date
this.chartDataIndicatorUpper[i].Indicator // the upper indicator
]);
}
for (i; i < indicatorLowerDataLength; i += 1) {
this.indicatorLowerDataArray.push([
this.chartDataIndicatorLower[i].Date, // the date
this.chartDataIndicatorLower[i].Indicator // the lower indicator
]);
}
// Add a null value for the end date
if (candleStickDataLength > 0) {
var endDateChartCandleStick = this.chartDataCandleStick[candleStickDataLength - 1].Date;
this.chartDataCandleStick = [].concat(this.chartDataCandleStick, [
[endDateChartCandleStick, null, null, null, null]
]);
}
if (indicatorUpperDataLength > 0) {
var endDateChartIndicatorUpper = this.chartDataIndicatorUpper[indicatorUpperDataLength - 1].Date;
this.chartDataIndicatorUpper = [].concat(this.chartDataIndicatorUpper, [
[endDateChartIndicatorUpper, null, null, null, null]
]);
}
if (indicatorLowerDataLength > 0) {
var endDateChartIndicatorLower = this.chartDataIndicatorLower[indicatorLowerDataLength - 1].Date;
this.chartDataIndicatorLower = [].concat(this.chartDataIndicatorLower, [
[endDateChartIndicatorLower, null, null, null, null]
]);
}
if (!this.chart) {
this.chart = new StockChart(this.chartOptions);
}
}
afterSetExtremes(e: { min: number; max: number }) {
console.log('Here we should load data. min: ' + e.min + ' max: ' + e.max);
// this.getChartData(e.min, e.max);
}
ngOnInit() {
this.chartOptions = {
rangeSelector: {
buttons: [
{
type: 'hour',
count: 1,
text: '1h'
},
{
type: 'day',
count: 1,
text: '1d'
},
{
type: 'week',
count: 1,
text: '1w'
},
{
type: 'month',
count: 1,
text: '1m'
},
{
type: 'year',
count: 1,
text: '1y'
},
{
type: 'all',
text: 'All'
}
],
inputEnabled: false, // it supports only days
selected: 0 // all
},
title: {
text: 'AAPL Historical'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: this.chartDataCandleStick
}
},
scrollbar: {
liveRedraw: false
},
xAxis: {
events: {
afterSetExtremes: this.afterSetExtremes
},
minRange: 3600 * 1000 // one hour
},
yAxis: [
{
labels: {
align: 'right',
x: -3
},
title: {
text: 'OHLC'
},
height: '80%',
lineWidth: 1,
resize: {
enabled: true
}
},
{
labels: {
align: 'right',
x: -3
},
title: {
text: 'Volume'
},
top: '90%',
height: '10%',
offset: 0,
lineWidth: 1
}
],
series: [
{
type: 'candlestick',
zoomType: 'x',
name: 'AAPL',
id: 'aapl',
data: this.candleStickDataArray,
dataGrouping: {
enabled: false
}
},
{
type: 'column',
zoomType: 'x',
name: 'Volume',
data: this.volumeDataArray,
yAxis: 1,
dataGrouping: {
enabled: false
}
},
{
type: 'spline',
zoomType: 'x',
name: 'indicatorUpper',
id: 'indicatorUpper',
data: this.indicatorUpperDataArray,
dataGrouping: {
enabled: false
}
},
{
type: 'spline',
zoomType: 'x',
name: 'indicatorLower',
id: 'indicatorLower',
data: this.indicatorLowerDataArray,
dataGrouping: {
enabled: false
}
},
{
type: 'flags',
name: 'Flags on series',
data: [
{
x: 946980000000,
title: 'Buy',
text: 'Some event with a description'
},
{
x: 946980060000,
title: 'Sell',
text: 'Some event with a description'
},
{
x: 946980060001,
title: 'Short',
text: 'Some event with a description'
},
{
x: 946980120000,
title: 'Buy',
text: 'Some event with a description'
},
{
x: 946980120001,
title: 'Buy',
text: 'Some event with a description'
},
{
x: 946980180000,
title: 'Sell',
text: 'Some event with a description'
},
{
x: 946980180001,
title: 'Short',
text: 'Some event with a description'
},
{
x: 946980240000,
title: 'Buy',
text: 'Some event with a description'
},
{
x: 946980240001,
title: 'Buy',
text: 'Some event with a description'
}
],
onSeries: 'dataseries',
shape: 'squarepin'
}
]
};
}
}