【问题标题】:How to check if the current routing parameters has been modified using Angular Routing如何使用 Angular Routing 检查当前路由参数是否已被修改
【发布时间】:2019-12-14 05:49:16
【问题描述】:

最初,当我基于当前路由链接登陆应用程序的主页时,我正在获取路由器参数并作为参数传递给 API 以获取数据,此调用应在 OnInit 和从下次每当用户更改路由时,我必须根据路由器参数调用不同的函数将其发送到后端。仅当路由器资源 URI 已更改时,我才必须调用函数。请帮我看看如何检查路由器链接是否已更改。

用于在@ngOnInit 中获取当前路由器参数的代码不确定如何检查路由器参数何时更改的条件。

 this.route.params.pipe(takeUntil(this.unsubscribe$)).subscribe(params => {

      this.resourceURI = params['resourceURI'];
      this.fetchDataOnInit(this.resourceURI);
    });

// 必须在这里检查一些条件,并从第二次开始调用其他一些我不知道如何尝试的函数。

【问题讨论】:

  • 你订阅了一个 observable,这意味着任何时候参数改变这个订阅应该导致 observable 发出一个值。这个值被广播给所有的观察者,就像你在 ngOnInit 中的组件一样。在您的订阅中尝试console.log(params);

标签: angular angular-routing


【解决方案1】:

您可以使用first() 运算符选择第一个值,并使用skip(1) 跳过第一个值。

   const resourceURI$ = this.route.params.pipe(pluck('resourceURI'));

   // handle first emitted value
   resourceURI$.pipe(
       first(),
       takeUntil(this.unsubscribe$)
   ).subscribe(resourceURI => {
       this.resourceURI = resourceURI;
       this.fetchDataOnInit(resourceURI);
   });

   // skip first emitted value
   resourceURI$.pipe(
       distinctUntilChanged(),
       skip(1),
       takeUntil(this.unsubscribe$)
   ).subscribe(resourceURI => {
       // do work with second, third, forth, etc..
   });

【讨论】:

  • 感谢您的回答。但是我必须在 OnInit 中只进行一次第一次调用,并且从第二次开始,每当我更改路由参数时,我都必须进行第二次调用。在这里如何检查第一个资源 URI 和第二个资源 URI 之间是否存在差异?
  • @AD_SK 我已经更新了答案。你只听不同的价值观。 learnrxjs.io/operators/filtering/distinctuntilchanged.html
  • 但是在这里我看到第一次调用再次发生,当路由器更改时我必须跳过第一个函数并只调用第二个函数。
猜你喜欢
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-15
  • 2018-05-18
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多