订阅结果中引用的角类变量未定义

时间:2019-05-03 19:27:13

标签: angular typescript observable subscribe

listConstituents在该类中为DECLARED,在ngOnInit中为INITIALIZED。 getConstituents函数的第一行是对getChildren的调用(它发出一个http请求)。

在订阅中,返回的“数据”很好,但是listConstituents是未定义的,并且从不设置:

export class ...
constructor() {}

  listConstituents: Constituent[];

  ngOnInit(): void {
    // debugger shows this next line is correct:  Array(0) []
    this.listConstituents = new Array<Constituent>();
  }

  getConstituents() {
      this.dataService.getChildren(this.ProdID, 'Constituent').subscribe(
        data => {   **<-- return array of any**
          for (let i = 0; i < data.length; i++) {
             let x = <Constituent>data[i];  <-- x cast to Constituent
             if ( x.Active ) {  <-- correctly accesses this part of Constituent
                this.listConstituents.push(x);   <-- ***this.listConstituents is undefined !***
              }
          }
        }
      etc.

3 个答案:

答案 0 :(得分:1)

我猜想getConstituents()在onInit之前被调用,或者在onInit之前以某种方式执行。

像这样声明成员变量。

listConstituents: Constituent[] = new Array<Constituent>();

答案 1 :(得分:0)

这是因为您的这个被称为get Children函数。将此引用分配给self并使用self访问父类的listConstituent会有所帮助。

getConstituents() { 
    let self = this;
    this.dataService.getChildren(this.ProdID, 'Constituent')
                    .subscribe( data => { **<-- return array of any** for (let i = 0; i < data.length; i++) { let x = <Constituent>data[i]; <-- x cast to Constituent if ( x.Active ) { <-- correctly accesses this part of Constituent self.listConstituents.push(x); <-- ***this.listConstituents is undefined !*** } } 
}

答案 2 :(得分:0)

我会推荐Karthik的建议(声明时只需实例化它)。

由于您使用的是匿名函数和简洁的方法,因此您的this应该正确(我不同意Ankur的建议)

我还想提供另一种方式来将项目推入数组:

this.dataService.getChildren(this.ProdID, 'Constituent').subscribe(
    (data: Array<Constituent>) => {
      this.listConstituents.push(...data.filter(x => x.Active));
    }