0

在我的 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
 }
}
}

如果我单击按钮执行该方法,一切正常。我怎样才能一个接一个地执行这些方法?

4

1 回答 1

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();
    });
}
于 2017-05-24T13:30:20.780 回答