TypeScript-等待可观察/承诺完成,然后返回可观察 [英] TypeScript - wait for an observable/promise to finish, and return observable
问题描述
我对TypeScript& RxJS,我试图在另一个Observable
完成后返回一个Observable
:
I am quite new to TypeScript & RxJS, and I am trying to return an Observable
after another Observable
is finished:
public myObservable = () : Observable<boolean> => {
console.log('retrieving the token in DB');
return Observable.create(observer => {
setTimeout(() => {
observer.next(true);
observer.complete();
}, 5000);
});
}
public makeRequest = (): Observable<any> => {
return this.myObservable().subscribe(
function (x) {
console.log('I have the token, now I can make the HTTP call');
return this.http.get('http://jsonplaceholder.typicode.com/posts/1')
.map( (responseData) => {
return responseData.json();
})
.map((item:any) => {
return {
id: item.id,
userId: item.userId,
title: item.title,
body: item.body
};
});
},
function (err) {
console.error('Error: ' + err);
},
function () {
console.log('Completed');
});
}
我收到此错误:无法将返回的表达式类型订阅分配给类型Observable<any>
".
I received this error: "Returned expression type subscription is not assignable to type Observable<any>
".
我完全理解这里的错误(一个Observable就像是一个流,而订阅是观察"该流的事实),但是我看不到如何等待" Observable
(或承诺)完成以返回新的Observable
.我该怎么办?
I totally understand the error here (an Observable is like a stream, and a subscription is the fact of "observing" that stream), but I don't see how to "wait" for an Observable
(or a promise) to finish to return a new Observable
. How can I do that?
推荐答案
问题是我们使用.subscribe
将observable转换为不同类型...-我们不应该这样做(它不会返回observable)
The problem is that we convert observable into different type... with .subscribe
- while we should not (it does not return observable)
public makeRequest = (): Observable<any> => {
return this.myObservable().subscribe(
... // this is wrong, we cannot return .subscribe
// because it consumes observable and returns ISusbcriber
);
}
当我们有一个可观察的...时,我们应该只获取其结果,并使用.map将其转换为其他内容
When we have an observable... we should just take its result and use .map to convert it to something else
FlatMap
运算符将一个Observable发出的项目转换为Observables,然后 将这些排放物的排放量统一为一个可观察的
FlatMap
operatortransform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable
public makeRequest = (): Observable<any> => {
return this.myObservable()
.flatmap((x) => return this.http
.get('http://jsonplaceholder.typicode.com/posts/1')
.map( (responseData) => {
return responseData.json();
})
...
在此处查看所有详细信息
Check all the details here
这篇关于TypeScript-等待可观察/承诺完成,然后返回可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!