我正在尝试使用 angular 2 和 chart.js(通过 ngcharts)为图表构建仪表板。我想要一组图表,每个图表都通过自定义间隔的 http 请求进行更新。
现在我有三个单独的图表调用将数据推送到一个数组。我在下一次迭代时遇到了麻烦——如果我再次推送到数组,我最终会得到另外 3 个图表。我希望数组中的订阅者在间隔发出时更新新数据。
对于如何为我的用例正确构建组件/服务/http 关系,我有点困惑。我觉得我很接近,但我肯定错过了什么。如何获取间隔/订阅者关系以映射到 View 并按间隔更新现有图表? 任何帮助都会很棒!
现在:
服务:
我在这里实现间隔:
getSingleChartObsinterval(id: number, interval: number) : Observable<Graph> {
return Observable.interval(interval).flatMap(() => this.getSingleChartobs(id));
}
getSingleChartobs(id: number) : Observable<Graph> {
return this.jsonp.get(“api location”)
.map(response => this.extractJsonData(response, id) as Graph)
}
extractJsonData 只是获取响应并对其进行操作以使用图表 JS。它返回一个 Graph 对象,该对象具有易于使用的属性。我无法控制 API,因此无法重新配置响应以包含多个图表。
组件:
import { Component } from '@angular/core';
import { ChartsModule } from 'ng2-charts/ng2-charts';
import { ChartService } from './chart.service';
import { Graph } from './graph';
import { OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'ab-chart',
styles: [`
.chart {
display: block;
}
`],
templateUrl: 'app/chart.component.html'
})
export class ChartComponent implements OnInit {
ngOnInit(): void {
console.log("Chart component init");
this.getSingleChart(3, 5000);
this.getSingleChart(5, 4000);
this.getSingleChart(6, 5000);
}
graph: Graph;
graphs: Graph[] = [];
constructor(
private chartService: ChartService
) {}
getSingleChart(id: number, interval: number): void {
this.chartService.getSingleChartObsinterval(id, interval)
.subscribe(x =>
this.graphs.push(x)
);
}
}
观点:
<div *ngFor="let graph of graphs" class="chart-container">
<base-chart
class="chart"
[datasets]="graph.datasets"
[labels]="graph.labels"
[options]="graph.options"
[chartType]="graph.type">
</base-chart>
</div>
最佳答案
由于每个图表都有自己的 id
(我假设它是唯一的)所以我只需更改 getSingleChart()
方法来更新 graphs
特定键的对象。请注意,我将 graphs
属性从数组更改为对象:
graphs: {[key: number]: Graph} = {};
getSingleChart(id: number, interval: number): void {
this.chartService.getSingleChartObsinterval(id, interval)
.subscribe(x => this.graphs[id] = x);
}
get graphIds() {
return Object.keys(this.graphs);
}
然后在模板中你需要迭代键数组(你可以迭代graphs
对象:
<div *ngFor="let id of graphIds" class="chart-container">
<base-chart
class="chart"
[datasets]="graphs[id].datasets"
[labels]="graphs[id].labels"
[options]="graphs[id].options"
[chartType]="graphs[id].type">
</base-chart>
</div>
关于javascript - 如何使用间隔更新可观察数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40226376/