【发布时间】:2019-02-05 08:22:57
【问题描述】:
我正在编写一个服务函数,它应该在哪里回复产品的最新价格。我连接到我的服务器 - 使用 websocket 并使用 Rxjs observable 获得 DataStream,现在服务层中的函数应该只回复值而不是 Observable 对象。
我正在尝试的示例代码
public getRealTimePrice(id: string): number {
let ws = new $WebSocket('/price?Id=' + id + '&connectionId=' + this.randomUUID());
this.priceWebsocket = ws;
this.priceWebsocket.getDataStream()
.map(msg => JSON.parse(msg.data).price)
.subscribe(responseNumber => {
return responseNumber // by the time execution reaches here the context is changed.
});
// I am not returning anything on the function level - which results in a compilation error as per typescript.
}
但由于很明显的原因,我无法返回数字 - 因为它在订阅回调中,上下文发生变化并且函数是异步的
如何等待 Observable 的回复,然后只返回 observable 中收到的值。
【问题讨论】:
标签: javascript rxjs observable