ngOnInit()运行methos并行?

时间:2017-05-24 13:23:36

标签: angular ngoninit

在我的Angular项目中,我从ConnectToHueBridge()调用方法listAllGoups()ngOnInit()。在我看来,两种方法都将并行执行。但我需要先运行ConnectToHueBridge()然后listAllGoups()。我怎么能这样做?

var MyHue = new huepi();

@Component({

selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<div>
  <ul>
    <li *ngFor="let group of lightgroups">
      {{group}}
    </li>
  </ul>
</div>
<Button (click)="listAllGroups()"> Get Groups</Button>`,
 })

export class AppComponent  {
  name = 'Angular';
  lightgroups: string[] = [];

constructor(){
}

ngOnInit(){
  this.ConnectToHueBridge(MyHue);
  this.listAllGroups();
}

listAllGroups(){
  for(var g in MyHue.Groups){
    this.lightgroups.push(g);
  }
  console.log("done loading groups");
}

 ConnectToHueBridge(MyHue:any){
 //do some stuff
 }
}
}

如果我点击按钮执行该方法一切正常。 我怎样才能在彼此之后执行这些方法?

1 个答案:

答案 0 :(得分:1)

你必须使它们可观察。

ConnectToHueBridge(MyHue:any): Observable<any> {
    //do some stuff
    return Observable.of(true);
}

然后,在ngOnInit执行此操作

ngOnInit() {
    this.ConnectToHueBridge('xxx').subscribe(data => {
        // data = true, you can change it in your function
        this.listAllGroups();
    });
}