【发布时间】: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