首页 > 解决方案 > 在 Angular 函数中等待 Observable

问题描述

我有一项服务,通过发送 sql 查询来获取数据;

  getList(model:sqlModel):Observable<apiResultModel<sqlResultModel>>{
    return this.http.post<apiResultModel<sqlResultModel>>(this.apiUrl,JSON.stringify(model),httpOptions);
  }

我的服务运行顺利。但是在一个组件中我想使用这个传入的数据,我必须等待数据的到来。

 openInputPopup():void{
    const resModel = this.getSqlResult();--this should not go to the bottom line before it is completed 
    console.log('res',resModel);
    const modal = this.inputPopup.create({
      nzTitle: 'Component Settings',
      nzStyle:{'top':'20px', 'width':'60%'},
      nzContent: FormPopupModalComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzComponentParams: {   
        sqlResModel:resModel 
      },
      nzOnOk: () => new Promise(resolve => setTimeout(resolve, 1000))      
    });
    modal.afterClose.subscribe(a=>{
      var el = document.getElementById('popDeneme');
      this.popValue = modal.componentInstance.inputId;
    });
  }


  getSqlResult() :sqlResultModel{
    this.sqlModel.dbSourceId=1;
    this.sqlModel.limitperPage=1;
    this.sqlModel.pageNum=1;
    this.sqlModel.query="SELECT [CODE],[DEFINITION_] FROM [TEST].[dbo].[PRODUCTS]"
    var res = new sqlResultModel();
   
    this.sqlService.getList(this.sqlModel).subscribe(
      i=>{        
        res = i.Result;
        console.log('ok');
      }
    );

    return res;  --There should be no return before the getlist() function above is completed. Since getlist() is not complete, it returns the initial value and it doesn't work for me.  
  }

你建议我怎么做?我知道这是一个小问题,但我是编码新手,请帮忙

标签: angularobservable

解决方案


您可以使用前面提到的 Rxjs 运算符,但您也可以转换为 promise 并使用 await,如下所示:

而是返回这个 return this.sqlService.getList(this.sqlModel).toPromise()

并像这样使用它:

async openInputPopup():void{
const resModel = await this.getSqlResult();
// your code 
}

推荐阅读