Angular/RxJS:同步可观察

编程入门 行业动态 更新时间:2024-10-17 23:28:12
本文介绍了Angular/RxJS:同步可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个具有方法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:同步可观察

本文发布于:2023-11-27 23:30:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640035.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Angular   RxJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!