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

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

问题描述

我目前有一项服务,它向API发送HTTP请求以获取数据。我想从服务中对observable做一些逻辑,但我仍然想在我的Component中订阅Observable,这样我就可以将任何错误返回给Component和用户。

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返回给Component,以便我可以继续在那里做事。

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.

这样做的模式是什么?

What's the pattern to do this?

推荐答案

我觉得发布的模式和解决方案的多个是丑陋或不遵循可观察的模式(就像做回调一样)。

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 in a second Observable factory method.

所以以下内容:

So the following:

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

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

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

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