使用许多嵌套的switchMap是不好的做法吗? [英] Is it bad practice to use many nested switchMap?

查看:130
本文介绍了使用许多嵌套的switchMap是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有http拦截器.在该拦截器中,更改请求之前,我需要先打开加载程序.
让我真正担心的是,我最终有很多切换图.

I have http interceptor. In that interceptor, before I change the request, I need a loader to turn on.
What really worries me is that I end up having lots of switchmaps.

为什么?

  1. 加载程序是异步的
  2. 我还需要将从拦截器传递的消息转换为加载程序服务.翻译消息也是异步的.在拦截器中,我应该在加载程序和翻译完成后运行请求

我在加载程序服务中做什么

showLoader(message){
    return this.translateService.get(message).pipe(switchMap( (translatedMessage)=>{
            this.loader$ = from(this.loadingController.create({message: translatedMessage}));
            return this.loader$.pipe(switchMap((loader)=>{
              return from(loader.present());
            }));
          }));
    }

在我的拦截器中

intercept(request: HttpRequest<any>, next: HttpHandler) {
        return this.loaderService.showLoader("WAITING").pipe(
            take(1),
            switchMap( ()=>{

所以已经嵌套了3个switchmap.在它下面,我需要2到3个以上的切换图(一个用于从存储中获取令牌,另一个用于其他操作).基本上以5个switchmap结束.

so there are already 3 switchmaps nested. and below it, i need 2 or 3 more switchmaps (one for getting tokens from storage and one for something else). basically end up with having 5 switchmaps.

问题:嵌套所有这些switchMap是不好的做法吗?

推荐答案

使用许多switchMap很好,尤其是当您需要异步行为时,不良的做法是接触数据流之外的内容.

It's fine to use many switchMap especially when you need asynchronous behaviour, the bad practice is to touch things outside of the data stream.

在您的代码中,this.loader$是它的一个示例,与其在流之外使用变量,不如尝试构建一个在内部执行您想要的所有事情的管道.

In your code this.loader$ is an example of it, instead of using variables outside of a stream try to build a pipe that does everything you want inside of itself.

如果this.loadingController.createloader.presentPromise类似,甚至switchMap支持ObservablePromiseArrayIterator,您甚至可以省略from.

You can even omit from if this.loadingController.create and loader.present are Promise like, switchMap supports Observable, Promise, Array and Iterator.

您的代码可能就是这样

    public showLoader(message) {
        return this.translateService.get(message).pipe(
            switchMap(translatedMessage => this.loadingController.create({message: translatedMessage})),
            switchMap(loader => loader.present()),
        );
    }

这篇关于使用许多嵌套的switchMap是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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