RxJS-改进操作的分支

RxJS-改进操作的分支,rxjs,Rxjs,我使用的是Angular,它的HttpClient类。 我需要区分有效调用(HTTP 200)和错误调用(HTTP非200或自定义响应)。 目前我使用的是这种模式: const httpSource$ = this.httpClient.get<MyType>(url) const valid$ = httpSource$.pipe( filter(result => result.code === 0), tap(() => this.logger.de

我使用的是Angular,它的
HttpClient
类。
我需要区分有效调用(HTTP 200)和错误调用(HTTP非200或自定义响应)。
目前我使用的是这种模式:

const httpSource$ = this.httpClient.get<MyType>(url)
const valid$ = httpSource$.pipe(
    filter(result => result.code === 0),
    tap(() => this.logger.debug(...)),
    map(result => Result.valid(result.value))
)
const error$ = httpSource$.pipe(
    filter(result => result.code !== 0),
    tap(() => this.logger.debug(...)),
    map(result => Result.error(result.message, result.value))
)

return merge(valid$, error$).pipe(
    catchError(e => of(Result.error<FunReturnType>>(e.message)))
)
const httpSource$=this.httpClient.get(url)
const valid$=httpSource$.pipe(
过滤器(结果=>result.code==0),
点击(()=>this.logger.debug(…),
映射(result=>result.valid(result.value))
)
常量错误$=httpSource$.pipe(
过滤器(结果=>result.code!==0),
点击(()=>this.logger.debug(…),
映射(result=>result.error(result.message,result.value))
)
返回合并(有效$,错误$).pipe(
catchError(e=>of(Result.error>(e.message)))
)

我走对了路?我是否过度复杂化了(这可能只是
map
操作符上的if-else)?这可以进一步简化吗?

< P>我的意见是,我建议你考虑这样做:

我假设Result.valid和Result.error都是通过应用程序将api答案转换为可消费对象的静态助手

httpSource$.pipe(
点击(()=>this.logger.debug(…),
映射(结果=>{
如果(result.code==0){
返回Result.valid(Result.value);
}
否则{
Result.error(Result.message、Result.value);
}
}),
catchError(e=>of(Result.error>(e.message)))
);

这将解决您的两次调用问题,并使下一个开发人员更易于阅读。

此方法调用两次ajax请求否?@Yanis git当前是。但这是我将要解决的问题,这基本上是我“以前”的情况。如果我需要更复杂的逻辑呢?可能map clojure会变得太大,我更喜欢没有私人“助手”功能。双重呼叫可以通过共享操作符解决。不要建议您使用共享操作符,因为您将无法再次询问您的服务器(例如获取最新更新),因为我们始终会在第一次呼叫时返回答案。关于你一次又一次的映射,你可以调用静态方法,就像你已经拥有的一样,或者一步一步地使用管道映射。分区操作符呢?也许它可以简化,并且解决了多次调用的问题!好主意,如果你的真实情况如此严重,你应该走这条路
httpSource$.pipe(
    tap(() => this.logger.debug(...)),
    map(result => {
        if(result.code === 0) {
            return Result.valid(result.value);
        }
        else {
            Result.error(result.message, result.value);
        }
    }),
    catchError(e => of(Result.error<FunReturnType>>(e.message)))
);