【问题标题】:Conditionals and assignments before switchmap in Angular7Angular7中switchmap之前的条件和赋值
【发布时间】:2020-05-23 19:35:16
【问题描述】:

我仍在尝试了解 Angular 中的 rxjs,但我仍然不完全了解管道和运算符。我需要有关这种情况的帮助,以及正确的方法是什么(已经尝试过一种肮脏的方法并完成了它,但感觉不对)。

我想在加载页面时获取一些数据,这些数据由路由中的参数引用。有两种情况,如果它有一个 id 它应该将它保存到一个局部变量,然后,获取数据并处理它。如果它没有任何 id 参数,它应该跳过数据获取。 我的代码是这样的:

        this.activatedRoute.params.pipe(
            //I want to save params.id to this.id here
            //I dont want to execute the switchmap if params.id is empty
            switchMap(params => this.establishmentService.getEstablishment(params.id))
        ).subscribe(/* process data */);

如何访问从本地变量的激活路由参数返回的数据,如果该参数为空,我如何避免 getEstablishment 函数?谢谢。

【问题讨论】:

    标签: angular rxjs angular7


    【解决方案1】:

    为此,您需要使用 tapfilter

    this.activatedRoute.params.pipe(
      tap(params => this.id = params.id), // saving id
      filter(params => !!params.id), // ignoring service until we have an id
      switchMap(params => this.establishmentService.getEstablishment(params.id)),
    ).subscribe(servieResult => {});
    

    【讨论】:

    • 谢谢,效果很好,我得看看tap功能
    • 不客气,点击执行像subscribe这样的回调,不会影响当前流值。
    【解决方案2】:

    首先,您可以轻松避免使用三元运算符执行 getEstablishment 来检查 params.id 是否为空

     this.activatedRoute.params.pipe(
                switchMap(params => params.id ? this.establishmentService.getEstablishment(params.id)) : params
            ).subscribe(/* process data */);
    

    【讨论】:

      猜你喜欢
      • 2019-10-08
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多