我有一个具有方法foo的服务.在方法内部,我订阅了一个可观察的(http客户端).
I have a service that has a method foo. Inside the method I subscribe to an observable (http-client).
foo () : boolean { let ret : false; this.http.get ("/blabla").subscribe ( (resp) => { ret = true; } return ret; );我喜欢从foo返回一个布尔值,该值取决于get.这不起作用,因为http.get是异步的-在http.get完成之前调用return.
I like to return a boolean value from foo that depends on the get. That is not working because http.get is asynchrouns - return is called before http.get finished.
如何使它同步?
编辑
在这里不能选择返回observable布尔值. 那是因为我处理了get in foo的响应(此处未显示),但是我还需要根据foo的返回采取行动.
Returning the observable instead boolean is not an option here. That is because I handle the response of get in foo (not shown here) but I also need to act out of foo depending of its return.
EDIT2
我用管子和水龙头扩展了样品.现在,我返回服务外部的http.get-observable,并用tap处理http.get-result.
I extended my sample with pipe and tap. Now I return the http.get-observable for outside the service and I process the http.get-result with tap.
foo () : Observable <any> { return this.http.get ("/blabla").pipe (tap (x => handlehere ())); }据我所知,它只有一个丑陋之处.我有解析foo内部和外部的get-result的复杂性.我希望在foo之外使用一个简单的布尔值.
As far I see there is only one uglyness with it. I have the complexity of parsing the get-result inside AND outside of foo. I would prefer a simple boolean outside of foo.
推荐答案此方法只能异步运行,因此您没有太多选择.退回烦人并订阅或退回诺言.也许,答应诺言会在理解方面满足您的更多需求.
This method can only run asynchronously so you don't have a lot of option. Returning the obsersable and subscribe or return a promise. Perhaps returning a Promise will suite more your need in term of comprehention.
为您服务:foo方法:
In your service : the foo method :
async foo() { const result = await this.http.get("/blabla").toPromise(); // do what you want with result return result; }如何命名:
this.myService.foo().then( (result) => { // Do what you want with the result });更多推荐
Angular/RxJS:同步可观察
发布评论