我正在使用D3.js开发条形图,我正在使用Observable从API中获取值。
ngOnInit() {
this.dataCollectionService
.getAllCurrencyData()
.subscribe(
(currData) => {
this.currencyData = currData;
});
this.initSvg();
this.initAxis();
this.drawAxis();
this.drawBars();
}
private initSvg() {
this.svg = d3.select("svg");
this.width = +this.svg.attr("width") - this.margin.left - this.margin.right;
this.height = +this.svg.attr("height") - this.margin.top - this.margin.bottom;
this.g = this.svg.append("g")
.attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")");
}
private initAxis() {
this.x = d3Scale.scaleBand().rangeRound([0, this.width]).padding(0.1);
this.y = d3Scale.scaleLinear().rangeRound([this.height, 0]);
this.x.domain(this.currencyData.map((d) => d.symbol));
this.y.domain([0, d3Array.max(this.currencyData, (d) => d.price_usd)]);
}
private drawAxis() {
this.g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + this.height + ")")
.call(d3Axis.axisBottom(this.x));
this.g.append("g")
.attr("class", "axis axis--y")
.call(d3Axis.axisLeft(this.y).ticks(5))
.append("text")
.attr("class", "axis-title")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("Dollar Value");
}
private drawBars() {
this.g.selectAll(".bar")
.data(this.currencyData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", (d) => this.x(d.symbol) )
.attr("y", (d) => this.y(d.price_usd) )
.attr("width", this.x.bandwidth())
.attr("height", (d) => this.height - this.y(d.price_usd) );
}
我面临的问题是,所有图表方法都在this.currencyData订阅所有值之前执行。因此没有显示聊天我将所有图表方法都放在订阅中,但它提供了帮助。我也尝试将服务调用放在构造函数中,但没有运气。
请问这个问题的解决方案吗?