angular - 在 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.
}
你建议我怎么做?我知道这是一个小问题,但我是编码新手,请帮忙
解决方案
您可以使用前面提到的 Rxjs 运算符,但您也可以转换为 promise 并使用 await,如下所示:
而是返回这个
return this.sqlService.getList(this.sqlModel).toPromise()
并像这样使用它:
async openInputPopup():void{
const resModel = await this.getSqlResult();
// your code
}
推荐阅读
- javascript - 两个相互调整的范围滑块
- amazon-web-services - 在 AWS 实例中看不到控制台日志
- amazon-web-services - 从 Lambda 中访问 cognito 用户属性
- java - Spring Boot JWT - JKS 文件和公钥
- json - 如何将 JSON 对象格式化为 bash 中的单独行
- javascript - 由于反应导航错误,无法运行 React Native App
- firebase - Flutter如何根据某个值从firebase对列表进行分组
- python - 如果位置的值为 0,则将所有像素设置为黑色
- asp.net-mvc - 列表
不包含“Patient_Name”的定义,也没有扩展方法“Patient_Name” - uilabel - didSet 未使用异步数据更新 UILabel.text