【问题标题】:How to fire subscribe only when param or one key-value pair of query param changes如何仅在参数或查询参数的一个键值对更改时触发订阅
【发布时间】:2021-06-23 03:08:05
【问题描述】:

我有以下情况,我只想在 url 的参数发生更改或查询参数中的 showList 更改时触发订阅。查询参数 page=0&size=5&sort=name,asc 的其余部分仅添加用于重新加载等情况或导航回相同的 url,并在添加 showList queryParam 后添加,这会导致订阅被触发两次。

以下方式的路线变化是我点击showList按钮

http://localhost:8080/org/acount/param1/param2?showList=true
http://localhost:8080/org/acount/param1/param2?showList=true&page=0&size=5&sort=name,asc

第二次导航发生是因为当 showList 为 true 时,调用 api 来获取帐户列表,如果 api 返回非空结果,则设置页面、大小和排序。

如果按下隐藏按钮,路由将更改为此

http://localhost:8080/org/acount/param1/param2?showList=false

当按下返回按钮时,我也需要处理像 reload + 这样的情况。

我已经实施了以下方法来处理上述情况,但我知道这不是最好的解决方案:

this.params_subscribe = combineLatest([this.activatedRoute.params, this.activatedRoute.queryParams]).pipe(
      map(results => ({ param: results[0], query: results[1] }))
    ).subscribe(result => {
      let show_list: boolean = (result.query.showList === 'true');
      if ((JSON.stringify(result.param) !== JSON.stringify(this.prevParam)) || (result.query.showList !== this.prevQueryParam.showList)) {
        if (!this.from_ui || result.query.showList !== 'false') {
          if (result.param.teamId && result.param.breadcrumb) {
            ...
          }
          else {
            this.initialize()
          }
        }
      }
      this.prevParam = result.param;
      this.prevQueryParam = result.query;
    });

from_ui 用于在通过单击将 showList 设置为 false 的 hideList 按钮更改查询参数时阻止函数调用。

有没有更好的方法来处理这个问题?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以将distinceUntilChanged 运算符与自定义比较器一起使用。

    试试下面的

    combineLatest([
      this.activatedRoute.params, 
      this.activatedRoute.queryParams
    ]).pipe(
      map(results => ({ param: results[0], query: results[1] })),
      distinctUntilChanged((prev, curr) =>
        JSON.stringify(prev.result.param) === JSON.stringify(curr.result.param) &&
        prev.result.query.showList === curr.result.query.showList
      )
    ).subscribe(
      ...
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2016-09-11
      • 2020-06-03
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多