TypeScript - 等待 observable/promise 完成,然后返回 observable [英] TypeScript - wait for an observable/promise to finish, and return observable

查看:69
本文介绍了TypeScript - 等待 observable/promise 完成,然后返回 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".

I received this error: "Returned expression type subscription is not assignable to type Observable<any>".

我完全理解这里的错误(Observable 就像一个流,订阅是观察"该流的事实),但我不知道如何等待"一个 Observable (或一个 promise) 来完成返回一个新的 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 转换成不同的类型——而我们不应该(它不返回可观察)

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
    );
}

当我们有一个 observable 时……我们应该只获取它的结果并使用 .map 将它转换为其他内容

When we have an observable... we should just take its result and use .map to convert it to something else

将 Observable 发出的项目转换为 Observables,然后将它们的排放扁平化为单个 Observable

FlatMap operator

transform 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 - 等待 observable/promise 完成,然后返回 observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆