Angular 等待http req单元完成(服务)

Angular 等待http req单元完成(服务),angular,service,subscribe,Angular,Service,Subscribe,在我的组件angular call services中,在执行所有代码之前,我需要等待和更改任何解决方案 read(idPos:string){ var choice = 0; this.menuItemsService.getAllDataMenuItemsByParentId(idPos).subscribe(data=> { choice = 1; // change Value to 1 if(data.length !=0){

在我的组件angular call services中,在执行所有代码之前,我需要等待和更改任何解决方案

read(idPos:string){
  var choice = 0;   
  this.menuItemsService.getAllDataMenuItemsByParentId(idPos).subscribe(data=> 
    { 
    choice = 1; // change Value to 1 
    if(data.length !=0){
     this.data =data;
    }   

    console.log(choice)
  })
  console.log(choice); // print 0 no change to =1

基本上,您不应该像在示例中那样将任何代码放在异步调用(subscribe)下面

请考虑这个:

read(idPos:string){
  var choice = 0;   
  this.menuItemsService.getAllDataMenuItemsByParentId(idPos).subscribe(data=> 
  { 
    choice = 1; // change Value to 1 
    if(data.length !=0){
     this.data =data;
    }   

    console.log(choice)

    this.continueRead(choice);
  })
  // console.log(choice); // <<< remove this line.
}

continueRead(choice: number) {
  console.log(choice); // <<< will print 1
}
read(idPos:string){
var选择=0;
this.menuItemsService.getAllDataMenuItemsByParentId(idPos).subscribe(数据=>
{ 
choice=1;//将值更改为1
如果(data.length!=0){
这个数据=数据;
}   
console.log(选项)
这个。继续阅读(选择);
})

//console.log(选项);//您必须将http调用后需要执行的所有代码移动到订阅回调中。这里有什么混淆?订阅回调只有在您可观察的http请求完成后才会触发我需要知道接收的数据长度,然后进行布尔更改,并调用其他服务,这取决于您可以执行这两个操作(设置布尔值并调用其他服务)在订阅回拨本身内部,就像@dexter已回答一样。如果建议不清楚,您可以详细说明您的问题。谢谢!@NinjaJamiThanks you!@dexter