未定义的变量已声明 whet 从 ngOnInit 上的 api 获取数据 [英] Undefined varibale already declared whet getting data from api on ngOnInit
问题描述
我正在尝试使用 angular 从 nodeJS API 获取数据,我声明了一个变量,我想影响服务器对它的响应,这是我的代码:
导出类 SondageSingleComponent 实现 OnInit、AfterViewInit {@ViewChild('containerPieChart') 元素:ElementRef;调查:任何 = {};当前用户:任何;统计数据:任何;颜色计数器:任意 = 0;d3Colors: any[] = ["#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d"];私人主机:D3.Selection;私人 svg: D3.Selection;私人宽度:数字;私人身高:数字;私人半径:数量;私有 htmlElement: HTMLElement;私人馅饼数据 = [];构造函数(私有 http: HttpClient,私人路线:ActivatedRoute,专用路由器:路由器,私人 toastr:ToastrService) { }ngOnInit() {this.route.params.subscribe(params => {this.http.get('/api/surveys/' + params.id).subscribe(survey => {this.survey = 调查;//console.log(this.survey)调试器this.http.get('/api/surveys/getStatistics/' + params.id).subscribe(statistics => {this.statistics = 统计数据;this.statistics.options.forEach(option => {this.pieData.push(option.number);option.color = this.d3Colors[this.colorCounter];this.colorCounter = this.colorCounter + 1;});});}, 错误 =>{如果(错误.状态 === 400){this.showError(error.error.error, 'Erreur!');if (error.error.error === 'Lesondage demandé n\'existe plus!') {this.router.navigateByUrl('/sondage');}}});});}
<小时>
从节点端成功传来的数据,当我试图将数据影响到调查变量并尝试时,谁能告诉我为什么无法读取this.survey?
可观察的黄金法则:不要嵌套订阅!
您似乎想要:
- 监听路由参数变化
- 根据路由参数发出 2 个 http 请求
- 根据 http 响应更新图表
听 this.route.params
是 #1 的良好开端.
其次,使用 switchMap
来运行一个新的 observable.并使用 forkJoin
并行调用多个 observable.
ngOnInit() {this.route.params.pipe(switchMap(params => forkJoin({调查:this.http.get('/api/surveys/' + params.id),统计:this.http.get('/api/surveys/getStatistics/' + params.id)}))). 订阅(结果 => {this.survey = result.survey;this.statistics = result.statistics;this.updateChart(result.statistics);},错误 =>this.handleError(错误));}私人句柄错误(错误){如果(错误.状态 === 400){this.showError(error.error.error, 'Erreur!');if (error.error.error === 'Lesondage demandé n\'existe plus!') {this.router.navigateByUrl('/sondage');}}}私人更新图表(统计){statistics.options.forEach(option => {this.pieData.push(option.number);option.color = this.d3Colors[this.colorCounter];this.colorCounter = this.colorCounter + 1;});}
演示:https://stackblitz.com/edit/angular-m4agxv>
角度 <8
forkJoin({})
仅在 RxJS 6.5 (Angular >= 8) 后可用.对于较早的版本,您必须传入一组可观察对象.
ngOnInit() {this.route.params.pipe(switchMap(params => forkJoin([this.http.get('/api/surveys/' + params.id),this.http.get('/api/surveys/getStatistics/' + params.id)]))). 订阅(结果 => {this.survey = 结果[0];this.statistics = 结果[1];this.updateChart(result[1]);},错误 =>this.handleError(错误));}
I'm trying to fetch data from nodeJS API with angular, I have a variable declared and I want to affect the response from server to it, here is my code :
export class SondageSingleComponent implements OnInit, AfterViewInit {
@ViewChild('containerPieChart') element: ElementRef;
survey: any = {};
currentUser: any;
statistics: any;
colorCounter: any = 0;
d3Colors: any[] = ["#3182bd", "#6baed6", "#9ecae1", "#c6dbef", "#e6550d"];
private host: D3.Selection;
private svg: D3.Selection;
private width: number;
private height: number;
private radius: number;
private htmlElement: HTMLElement;
private pieData = [];
constructor(
private http: HttpClient,
private route: ActivatedRoute,
private router: Router,
private toastr: ToastrService
) { }
ngOnInit() {
this.route.params.subscribe(params => {
this.http.get('/api/surveys/' + params.id).subscribe(survey => {
this.survey = survey;
// console.log(this.survey)
debugger
this.http.get('/api/surveys/getStatistics/' + params.id).subscribe(statistics => {
this.statistics = statistics;
this.statistics.options.forEach(option => {
this.pieData.push(option.number);
option.color = this.d3Colors[this.colorCounter];
this.colorCounter = this.colorCounter + 1;
});
});
}, error => {
if (error.status === 400) {
this.showError(error.error.error, 'Erreur!');
if (error.error.error === 'Le sondage demandé n\'existe plus!') {
this.router.navigateByUrl('/sondage');
}
}
});
});
}
the data coming successfully from node side and when I try to affect the data to survey variable and to try, any one can tell why can't read this.survey ?
Golden rule with observables: Don't nest subscriptions!
It looks like you want to:
- Listen for route param changes
- Make 2 http requests based on a route param
- Update a chart based on the http responses
Listening to this.route.params
is a good start for #1.
Secondly, use switchMap
to run a new observable. And use forkJoin
to call multiple observables in parallel.
ngOnInit() {
this.route.params.pipe(
switchMap(params => forkJoin({
survey: this.http.get('/api/surveys/' + params.id),
statistics: this.http.get('/api/surveys/getStatistics/' + params.id)
}))
).subscribe(result => {
this.survey = result.survey;
this.statistics = result.statistics;
this.updateChart(result.statistics);
},
error => this.handleError(error)
);
}
private handleError(error) {
if (error.status === 400) {
this.showError(error.error.error, 'Erreur!');
if (error.error.error === 'Le sondage demandé n\'existe plus!') {
this.router.navigateByUrl('/sondage');
}
}
}
private updateChart(statistics) {
statistics.options.forEach(option => {
this.pieData.push(option.number);
option.color = this.d3Colors[this.colorCounter];
this.colorCounter = this.colorCounter + 1;
});
}
DEMO: https://stackblitz.com/edit/angular-m4agxv
Angular < 8
forkJoin({})
is only usable since RxJS 6.5 (Angular >= 8). For earlier versions you will have to pass in an array of observables.
ngOnInit() {
this.route.params.pipe(
switchMap(params => forkJoin([
this.http.get('/api/surveys/' + params.id),
this.http.get('/api/surveys/getStatistics/' + params.id)
]))
).subscribe(result => {
this.survey = result[0];
this.statistics = result[1];
this.updateChart(result[1]);
},
error => this.handleError(error)
);
}
这篇关于未定义的变量已声明 whet 从 ngOnInit 上的 api 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!