这个。<variable>在方法中是未定义的

时间:2017-09-12 09:26:08

标签: angular typescript this observable

我无法在类方法中访问类变量。

这是我的班级:

[imports, decorator......]
export class CardboardComponent implements OnInit {
  operations: Operation[];
  workplaces: Workplace[];
  workplaceGroups: WorkplaceGroup[];
  rowLeadItems: String[];

  constructor(private cardboardService: CardboardService) { }

  ngOnInit() {
    this.getData();
    this.createRowLeadItems();
  }

  getData() {
    console.log('Data started');
    console.log(this);
    this.cardboardService.getOperations()
      .subscribe(operations => {
        if (operations != undefined) {
          this.operations = operations;
        }
      });
    console.log('Data finished');
  }

  createRowLeadItems() {
    console.log('Row Lead started');
    console.log(this);
    console.log('Operations: ' + this.operations);
    console.log('Row Lead finished');
  }

}

控制台输出如下: Console

我不知道为什么this.operations在generateRowLeadItems()中未定义,当&#34; this&#34;工作正常,我可以在控制台中看到它。

1 个答案:

答案 0 :(得分:0)

实际上您的getdata是异步的,因此在createRowLeadItems()完成之前,getdata()将会执行一些从您的服务获取数据的时间createRowLeadItems()。最好在getdata()

中调用createRowLeadItems()函数

移除ngOnInit()内的来电getdata(),然后在getData() { console.log('Data started'); console.log(this); this.cardboardService.getOperations() .subscribe(operations => { if (operations != undefined) { this.operations = operations; createRowLeadItems(); <-------- calling here } }); console.log('Data finished'); } 内打电话

$JAVA_HOME/bin/keytool -genkey -alias tomcat -keyalg RSA