javascript - 如何访问函数范围之外的变量Angular 9
问题描述
我正在学习角度,我正在尝试访问范围之外的变量值。我试过使用this
. 没用,帮帮我
export class DashboardComponent {
private population: number;
private country: string;
constructor(private dummyService: DummyService) {
this.myData();
}
myData(){
this.dummyService.getList().subscribe((data) => {
this.response = data;
this.population = this.response.map(data => data.population);
this.country = this.response.map(data => data.country);
//able to console it here
});
//not able to console it here
}
chart1 = {
data: {
labels: this.country,// want to access it here
datasets: [{
label: 'population',
data: this.population, // want to access it here
backgroundColor: 'transparent',
borderColor: '#5b6582',
borderWidth: 2
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
fontColor: 'rgba(0,0,0,.6)',
fontStyle: 'bold',
beginAtZero: true,
maxTicksLimit: 8,
padding: 10
}
}]
},
responsive: true,
legend: {
position: 'bottom',
display: false
},
}
};
ngOnInit() {
new Chart('chart-line', {
type: 'line',
data: this.chart1.data,
options: this.chart1.options
});
}
解决方案
您应该在获取数据方法之前创建变量chart1
并创建initChart()
和调用。
export class DashboardComponent {
private population: number;
private country: string;
chart1 : any;
constructor(private dummyService: DummyService) {
this.myData();
}
myData(){
this.dummyService.getList().subscribe((data) => {
this.response = data;
this.population = this.response.map(data => data.population);
this.country = this.response.map(data => data.country);
//able to console it here
this.initChart();
});
//not able to console it here
}
initChart(){
let seft = this;
chart1 = {
data: {
labels: self.country,// want to access it here
datasets: [{
label: 'population',
data: self.population, // want to access it here
backgroundColor: 'transparent',
borderColor: '#5b6582',
borderWidth: 2
},
]
},
options: {
scales: {
yAxes: [{
ticks: {
fontColor: 'rgba(0,0,0,.6)',
fontStyle: 'bold',
beginAtZero: true,
maxTicksLimit: 8,
padding: 10
}
}]
},
responsive: true,
legend: {
position: 'bottom',
display: false
},
}
};
}
ngOnInit() {
new Chart('chart-line', {
type: 'line',
data: this.chart1.data,
options: this.chart1.options
});
}
推荐阅读
- regex - 正则表达式匹配除每行最后 2 个字符串之外的所有字符串
- python - Gurobi 给出了一组 C### 类型的解决方案
- python - 将一个ndarray的元素附加到python中的另一个ndarray时输出错误
- google-bigquery - 在选择 SQL 时插入 BigQuery 动态查询
- asp.net - 共享网站的域的 IIS URL 重写
- kubernetes - 使用 nginx/traefik 入口控制器自定义 vhost 配置
- android - 为 android 创建 facebook 的图像选择器
- java - 递归 Java 方法
- android - 滚动 recyclerview 时,Android 应用程序在三星等设备上崩溃
- ruby-on-rails - 对acts_as_votable 使用ajax 来避免页面重新加载