等待订阅角度

时间:2020-07-13 14:02:07

标签: angularjs angular angular-material

我需要等待订阅,然后将结果分配给angular 7中的特定变量,但是该代码没有在等待我的代码,就像这样。

async getItemsbyId(id) {
console.log('2')
 await  this.stockService.getStocks(id).subscribe(
   (res: any) => {
   console.log('3')
    this.data = res.data;
    return this.data;
  },
  err => {
    console.log(err);
  },
  () => {
    this.http_item = null;
  }
);
console.log('4')
} 

get_value(){
console.log('1')
this.getItemsbyId(5);
console.log('5')
}

我需要按此顺序依次控制台(1,2,3,4,5),但我得到(1,2,4,5,3),请提供此问题的答案

1 个答案:

答案 0 :(得分:1)

const stocks = await this.stockService.getStocks(id).toPromise();
// DO STUFF this.data = stocks.data;