使用 RxJS 从订阅中返回一个 Observable [英] Return a Observable from a Subscription with RxJS

查看:29
本文介绍了使用 RxJS 从订阅中返回一个 Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一项服务,可以向 API 发出 HTTP 请求以获取数据.我想对服务中的 observable 执行一些逻辑,但我仍然希望在我的组件中订阅 Observable,以便我可以将任何错误返回给组件和用户.

I currently have a service that do a HTTP request to an API to fetch data. There are some logic that I want to do to the observable from within the service, but I still want to also subscribe to the Observable in my Component so that I can return any errors to the Component and to the user.

目前我这样做:

// service.ts
getData(): Observable<any> {
    return this.http.get(url).pipe(catchError(this.handleError)
}

// component.ts
ngOnInit() {
    this.service.getData().subscribe(res => {
        // Do my logic that belong to the service.ts
        // ...

        // Do my logic that belongs in the component.ts
        // ...
    }, err => this.errors = err)
}

我想做的是重构它,以便我在 getData() 方法中处理与订阅和 service.ts 相关的逻辑,然后将带有 HTTP 响应和任何错误的 Observable 返回给组件以便我可以继续在那里做事.

What I would like to do is to refactor this so that I handle the logic related to the subscription and the service.ts within the getData() method, and then return an Observable with the HTTP response and any errors to the Component so that I can continue doing things there.

这样做的模式是什么?

推荐答案

我觉得发布的多个模式和解决方案都很丑陋";或者不遵循 Observable 模式(比如做回调).

I feel like multiple of the patterns and solutions posted is "ugly" or does not follow the Observable pattern (Like doing callbacks).

我想出的最简洁、最类似于RxJS"的解决方案是将服务方法的返回值包装在第二个 Observable 中.

The cleanest, most "RxJS"-like solution I came up with was to wrap the service method's return value in a second Observable.

所以如下:

// service.ts
getData(): Observable<any> {
    return new Observable(subscriber => {
        this.http.get(url)
          .pipe(catchError(this.handleError)
          .subscribe(res => {
              // Do my service.ts logic.
              // ...
              subscriber.next(res)
              subscriber.complete()
          }, err => subscriber.error(err))
    })
}

// component.ts
ngOnInit() {
    this.service.getData().subscribe(res => {
        // Do my component logic.
        // ...
    }, err => this.errors = err)
}

这篇关于使用 RxJS 从订阅中返回一个 Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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