未定义的变量已声明在ngOnInit上从api获取数据 [英] Undefined varibale already declared whet getting data from api on ngOnInit

查看:197
本文介绍了未定义的变量已声明在ngOnInit上从api获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从angularJS的nodeJS API中获取数据,我声明了一个变量,并且希望影响服务器对它的响应,这是我的代码:

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');
          }
        }
      });
    });

  }


数据成功地来自节点端,当我尝试影响数据以调查变量并进行尝试时,任何人都可以说出为什么无法读取此内容.

解决方案

带有可观察值的黄金规则:请勿嵌套订阅!

您似乎想要:

  1. 收听路线参数更改
  2. 根据路由参数发出2个http请求
  3. 根据http响应更新图表

this.route.params是#1的良好开端.

其次,使用switchMap运行新的可观察对象.并使用forkJoin并行调用多个可观察对象.

 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;
  });  
}
 

演示: 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)
    ]))
  ).subscribe(result => {
    this.survey = result[0];
    this.statistics = result[1];
    this.updateChart(result[1]);
  }, 
    error => this.handleError(error)
  );
}
 

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:

  1. Listen for route param changes
  2. Make 2 http requests based on a route param
  3. 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)
  );
}

这篇关于未定义的变量已声明在ngOnInit上从api获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆