sha*_*non 2 promise observable rxjs angular
我需要等待一个承诺完成,然后用RxJS激活Angular 2中的一个observable.
更具体地说,我需要使用返回promises的第三方库来设置状态,并在发出GET请求之前将一些结果信息插入到我的HTTP头中:
export class LiveDataService {
private headersPromise;
constructor(public http: Http) {
this.headersPromise = $.connection('/init').then((state) => setupHeaders(state));
}
activate(route: string) {
return this.http.get('api/v1/' + route, { headers })
.Merge(anotherStateBasedObservable);
}
)
Run Code Online (Sandbox Code Playgroud)
除了,虽然我需要立即返回observable,如图所示,我也必须等待承诺完成才能调用http.get.
我可以想到几个方面需要3-4个阶段的翻译,但我觉得应该有一个相当直接的方法来做到这一点.
你真的需要一个可观察的回归吗?我会做这样的事情:
// getState caches the state promise, so '/init' gets requested only once
// but is lazy loaded
var _statePromise = null;
function getState() {
return _statePromise || (_statePromise = $.connection('/init'));
}
function routeChange(route) {
return getState()
.then(state => setupHeaders(state))
.then(headers => this.http.get('api/v1/' + route, { headers }));
}
Run Code Online (Sandbox Code Playgroud)
编辑
您可以使用flatMap或映射带有异步函数的observable flatMapLatest:
// routeSource is an RxJS Observable
var contentSource = routeSource.flatMapLatest(routeChange);
Run Code Online (Sandbox Code Playgroud)
编辑
你可以将promises转换为observables,反之亦然:Bridging Promises
这可能是你需要的:
// getState caches the state promise, so '/init' gets requested
// only once, but is lazy loaded
var _statePromise = null;
function getState() {
return _statePromise || (_statePromise = $.connection('/init'));
}
function Method(route) {
return Rx.Observable.fromPromise(this.getState())
.flatMap(state => setupHeaders(state)) // flatMap handles promises
.flatMap(headers => this.http.get('api/v1/' + route, { headers }))
.merge(anotherStateBasedObservable);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4456 次 |
| 最近记录: |