等待 http 请求单元完成 angular(服务)
wait http req unit finish angular (services)
在我的组件中 angular 调用服务 我需要等待并更改,然后才能执行所有代码 任何解决方案?
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
基本上,您不应像示例中那样将任何代码放在异步调用(订阅)下方。
相反,考虑一下:
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
}
在我的组件中 angular 调用服务 我需要等待并更改,然后才能执行所有代码 任何解决方案?
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
基本上,您不应像示例中那样将任何代码放在异步调用(订阅)下方。
相反,考虑一下:
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
}