Geo*_*y D 31 observable rxjs typescript
我对Typescript和RxJS很安静,我尝试返回一个observable,而不是其他observable完成:
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');
});
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:"返回的表达式类型订阅不能分配给类型Observable
".
我完全理解这里的错误(Observable就像一个流,而订阅是"观察"流的事实),但我不知道如何"等待"一个可观察的(或一个承诺)完成返回一个可观察的......
Rad*_*ler 23
问题是我们将observable转换为不同类型... with .subscribe
- 虽然我们不应该(它不返回observable)
public makeRequest = (): Observable<any> => {
return this.myObservable().subscribe(
... // this is wrong, we cannot return .subscribe
// because it consumes observable and returns ISusbcriber
);
}
Run Code Online (Sandbox Code Playgroud)
当我们有一个可观察的...我们应该只取结果并使用.map将其转换为其他东西
FlatMap
操作者将Observable发出的项目转换为Observables,然后将这些项目的排放量变为单个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();
})
...
Run Code Online (Sandbox Code Playgroud)
在这里查看所有细节
rbj*_*325 15
虽然flatMap()可能有效,但由于您没有传入使用的参数[请参阅param(x)],因此在此场景中使用的最佳运算符是forkJoin().
请参阅此示例:https://stackoverflow.com/a/38049268/1742393
Observable.forkJoin(
this.http.get('/app/books.json').map((res:Response) => res.json()),
this.http.get('/app/movies.json').map((res:Response) => res.json())
).subscribe(
data => {
this.books = data[0]
this.movies = data[1]
},
err => console.error(err)
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
67289 次 |
最近记录: |