我在Observable中有一个GET请求。我想将它的结果发送给Observer。不幸的是,它发送了未定义的值,因为它甚至在GET执行完成之前就会与观察者进行通信 - 这就是问题所在。
observer:Observer<any> = {
next: objectFromObservable => { SomeActionWith() }
}
let outputToObserver;
this.http.get(myUrl).map((programs)=>{
const mapped = programs.json() as Program[];
outputToObserver=mapped //here we always have desired object
return mapped;
})
.subscribe(
(res)=>{
return res; //here we always have desired object
}
)
//Here outputToObserver is undefined, so above lines are executed before mapping
let observable:Observable<any> = Observable.create(function (obserwator) {
observer.next(outputToObserver)
答案 0 :(得分:1)
你可以做这样的事情
getDataFromMyUrl() {
return this.http.get(myUrl).map((programs)=>{
const mapped = programs.json() as Program[];
return mapped;
})
}
从消费方面你可以做这样的事情
var getData = getDataFromMyUrl()
.subscribe(res => {
// Process the data here....
});
答案 1 :(得分:0)
你也可以用do来解决副作用,在这种情况下,代码可以更具可读性和线性。
let outputStream=new Subject()
this.http.get(myUrl).map((programs)=>programs.json())
.do(value=>outputStream.next(value))
.subscribe()
outputStream.subscribe()