这是我的 service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Headers } from '@angular/http';
@Injectable()
export class BarserviceService {
public http: Http;
people:any;
constructor(http: Http) {
this.http = http;
}
get() {
// return this.mediaItems;
let charts = this.http.get("http://localhost:3000/charts")
.map(response => { this.people = response.json()
console.log("pople", this.people)
});
return charts;
}
这是我的 barchart.component.ts
ngOnInit() {
// this.getEarthquakes();
this.options = {
chart: {
type: 'discreteBarChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 50,
left: 55
},
x: function(d){return d.label;},
y: function(d){return d.value;},
showValues: true,
valueFormat: function(d){
return d3.format(',.4f')(d);
},
duration: 500,
xAxis: {
axisLabel: 'X Axis'
},
yAxis: {
axisLabel: 'Y Axis',
axisLabelDistance: -10
}
}
}
this.data =
[{
values: [
]
}
]
this.baroneService.get().subscribe(c => {
// console.log("pep",this.people);
// this.media = c.charts
console.log( "media",this.media = c.charts)
this.data = this.media
console.log("pep",this.data);});
这将是我的JSON
{
"charts": [
{
"values": [
{
"label": "A",
"value": -29.765957771107
},
{
"label": "B",
"value": 0
} ]} ]}
是在service.ts文件中获取控制台pople中的JSON数据,但不明白如何在component.ts文件中获取它。我可以通过JSON数据显示图表并在 console.log("媒体",this.media = c.charts in component.ts。
您可以将服务注入约束。
喜欢。
import { Service Class Name } from 'location of service file';
然后您可以注入约束。
constructer(private nameofyourown:Service Class Name)
{
}
您可以使用服务中声明的所有变量。
这是语法。
Constructer Ex中使用的名称:
如果我这样使用。
Constructer(private name:serviceclassname)
您可以用这样调用变量。
name.variablename
variablename在服务内部声明您可以像上述语法一样使用它。