【问题标题】:prevent multiple http request rxjs on route防止路由上的多个http请求rxjs
【发布时间】:2021-09-14 14:25:31
【问题描述】:

我想验证每条更改路线上的会话,因此我订阅了这样的路线

this.router.events.subscribe((ev) => {
      if (ev instanceof NavigationStart) {
           this.checkSession();
      }
});

但这总是会产生重复的http请求,如何防止上一个请求未完成时重复请求http

【问题讨论】:

  • 为什么不使用Angular Guard 来处理会话检查?

标签: angular rxjs


【解决方案1】:

如果路由中有一个属性没有改变,那么你应该试试这个, distinctuntilchanged

this.router.events
  // custom compare for url
  .pipe(
    filter(ev => ev instanceof NavigationStart),
    distinctUntilChanged((prev, curr) => prev.url !== curr.url))
  .subscribe((ev) => {
    this.checkSession();
  });

【讨论】:

    【解决方案2】:

    最好使用switchMap

    this.router.events.pipe(
      filter(ev => ev instanceof NavigationStart)
      switchMap(() => this.checkSession()) // checkSession should return an observable
    ).subscribe();
    

    在checkSession里面,不是订阅,而是返回API。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-27
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 2021-03-22
      相关资源
      最近更新 更多