我有一个具有方法foo的服务。在方法内部,我订阅了一个可观察的对象(http客户端)。
foo () : boolean
{
let ret : false;
this.http.get ("/blabla").subscribe (
(resp) =>
{
ret = true;
}
return ret;
);
Run Code Online (Sandbox Code Playgroud)
我喜欢从foo返回一个布尔值,该值取决于get。这不起作用,因为http.get是异步的-在http.get完成之前调用return。
我该如何使它同步?
编辑
在这里不能返回observable而不是布尔值。那是因为我处理了get in foo的响应(此处未显示),但是我还需要根据foo的返回采取行动。
编辑2
我用管道和水龙头扩展了样品。现在,我返回服务外部的http.get-observable,并用tap处理http.get-result。
foo () : Observable <any>
{
return this.http.get ("/blabla").pipe (tap (x => handlehere ()));
}
Run Code Online (Sandbox Code Playgroud)
据我所知,它只有一个丑陋之处。我有解析foo内部和外部的get-result的复杂性。我更喜欢foo之外的简单布尔值。
xro*_*t35 10
此方法只能异步运行,因此您没有太多选择。退回烦人并订阅或退回承诺。也许返回诺言会在理解方面满足您的更多需求。
为您服务:foo方法:
async foo() {
const result = await this.http.get("/blabla").toPromise();
// do what you want with result
return result;
}
Run Code Online (Sandbox Code Playgroud)
怎么称呼:
this.myService.foo().then( (result) => {
// Do what you want with the result
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9554 次 |
最近记录: |