使用异步和等待在ionic中调用带有角度的http服务

时间:2019-07-06 17:34:36

标签: angular ionic-framework

我正在设计一个带有离子框架的应用程序,该应用程序会返回一个服务,以显示产品列表。当我调用API时,出现此错误

Property 'subscribe' does not exist on type 'Promise<Observable<Object>>'. Did you forget to use 'await'?

SERVICE.ts

async testCall() {
  const loading = await this.loadingCtrl.create({
    message : 'Please Wait...'
  });
  await loading.present();

  const headers = this.getHeaders();
  const foodList = await this.http.post('https://api/view', {
    paginate: 5,
    page: 1
  }, {headers});
  loading.dismiss();

  return await foodList.pipe(tap(_ => {
  })
  );
}

组件

 async ngOnInit() {
    await this.productService.testCall().subscribe((data: any) => {
      this.productService.list = data.result.data;
    });
  }

有关如何完成此操作的任何帮助?

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

服务

testCall() {   
  const headers = this.getHeaders();
  const foodList = this.http.post('https://api/view', {
    paginate: 5,
    page: 1
  }, {headers});

  return foodList.pipe(tap(_ => {
  }));
}

组件:

ngOnInit() {

  const loading = await this.loadingCtrl.create({
    message : 'Please Wait...'
  });
  loading.present();

  this.productService.testCall().subscribe((data: any) => {
      this.productService.list = data.result.data;
      loading.dismiss();
  });
}
  

提示:请注意,我是如何将“正在加载” UI调用移至组件的

答案 1 :(得分:0)

尝试一下

const foodList = await this.http.post('https://api/view', {
    paginate: 5,
    page: 1
  }, {headers}).toPromise();
this.productService.list = await this.productService.testCall();