如何使嵌套的Observable中的内部Observable错误或成功识别外部Observable?
为什么onNext
和onCompleted
在内部Observable
内未定义?
public updateDocument(item: Document): Observable<any> {
this.firstUseOfflineContainer();
let afiEdit = this.offlineData.afi.edit;
//outer observable
return Observable.create(observer => {
//inner observable
this.dataService.updateRequest(item).subscribe(
(next) => {
console.log("ok");
},
(err) => {
afiEdit.headers.push(item);
//how to throw error to outer observable
},
() => {
observer.onNext(item);
observer.onCompleted();
}
);
return () => console.log('cleanup message')
});
}
答案 0 :(得分:1)
我的理解是,当内部observable失败时,你的目标只是在外部observable中抛出一个错误。
所以代码看起来像这样:
//Define the inner observable (probably an http call in your case)
//I mocked your call failing or passing with a random 50/50 chance
var innerObservable = new Rx.Observable(observer => {
var didMockCallFail = Math.random() < .5;
if(didMockCallFail){
console.log('Inner observable call failed');
observer.error(new Error('Call failed!'));
} else {
console.log('Inner observable call returned data');
observer.next({lolData: 'I am data'});
}
})
//define the outer observable which just calls the inner observable
var outerObservable = new Rx.Observable(observer => {
innerObservable.subscribe(
data => observer.next(data),
err => observer.error(err)
)
});
outerObservable.subscribe(
next => console.log('Got data!'),
err => console.error('lol fail')
);
此外,请注意,如果要将变量传递给Observable并使该代码可重用/避免全局范围,则可以使用生成器函数,例如
function makeObs(someParam){
return new Rx.Observable(observer => {
observer.next(someParam);
})
}
如果您有任何疑问,请与我们联系。