【问题标题】:Observable subscribe timing issue可观察的订阅时间问题
【发布时间】:2018-02-22 17:59:22
【问题描述】:

我的组件中有一个服务,该服务有一个从服务器返回字符串值的方法。

服务:

getOrderBarcode(): Observable<string> {
    return this.http.get(this.baseUrl + 'barcode/getbarcode')
        // .map(this.extractData);
        .map(res => res as string )
}

组件:

let barcodeService = this.barcodeService.getOrderBarcode();
debugger;
barcodeService.subscribe(result => order.OrderBarcode = result);
console.log(order.OrderBarcode);
// rest of the logic

但是,当.subscribe被调用时,此时它并没有绑定值,经过调试我发现它在执行完类中的所有内容后都会应用该值,我该如何解决这个问题?

根据 cmets 更新并链接到另一个问题

服务方式:

getSomething(callback: (data) => void) {
    debugger;
    return this.http.get(this.baseUrl + 'barcode/getbarcode')
        // .timeout(1000)
        // .map(this.extractData);
        .map(res => res as string)
}

组件:

let a = this.barcodeService.getSomething((data) => {
    debugger;
    console.log(data);
});

这个调试器没有被命中...

【问题讨论】:

  • 这就是应该发生的事情。您订阅和使用 observables 的全部原因是 该过程是异步的。
  • 好的,感谢您为我指明了正确的方向,如果我返回的是单个值而不是流,是否可以在这里使用 Promise 代替?
  • 除了它可能是您更熟悉的模式之外,您希望从使用 observables 无法完成的 Promise 中获得什么?
  • 我不建议将两者混合使用,尽可能坚持使用一种异步范式。 RxJS 是内置在 Angular 中的,所以除非你有一大堆 promise-y 的东西可以与之交互,否则我会倾向于使用 observables。

标签: javascript angular typescript rxjs angular2-services


【解决方案1】:

您的示例代码

barcodeService.subscribe(result => order.OrderBarcode = result);
console.log(order.OrderBarcode);

修复

使用toPromise 并等待结果(或使用then)。

更多:https://www.learnrxjs.io/operators/utility/topromise.html

【讨论】:

  • 为什么有人会将可观察对象转换为仅用于调试的承诺?那只是开销。 do 运算符就是为此而生的
  • 谢谢,我确实想知道这一点,但我会认为上面提到的观点。你能扩大一点吗?
猜你喜欢
  • 2021-11-26
  • 2019-11-15
  • 1970-01-01
  • 2018-06-23
  • 1970-01-01
  • 2022-01-12
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多