Угловая переменная класса, на которую ссылается результат подписки, не определена - PullRequest
1 голос
/ 03 мая 2019

listConstituents ОБЪЯВЛЯЕТСЯ в классе и ИНИЦИАЛИЗИРУЕТСЯ в ngOnInit. Первая строка функции 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 ]

1 голос
/ 03 мая 2019

Я полагаю, что getConstituents () вызывается перед onInit или как-то иначе выполняется перед onInit.

Объявите переменную-член следующим образом.

listConstituents: Constituent[] = new Array<Constituent>();
0 голосов
/ 04 мая 2019

Я бы порекомендовал то, что порекомендовал Картик (просто создавая его, когда вы объявляете это).

Поскольку вы используете анонимные функции и краткие методы, ваш this должен быть правильным (я не согласен с тем, что предложил Анкур)

Я также хотел дать другой способ того, как вы помещаете элементы в массив:

this.dataService.getChildren(this.ProdID, 'Constituent').subscribe(
    (data: Array<Constituent>) => {
      this.listConstituents.push(...data.filter(x => x.Active));
    }
0 голосов
/ 03 мая 2019

Это потому, что ваша функция this называется функцией 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 !*** } } 
}
...