【问题标题】:Problem when trying to unsubscribe from route subscription尝试取消订阅路由时出现问题
【发布时间】:2021-04-21 19:51:45
【问题描述】:

我有一个困扰我的问题:)

我在服务中:

    const url = this.router.url;
    this.Subscription = router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        this.previousUrl = url ;
        url  = event.url;
      }
    });
  public unsubscribeNavigation() {
    this.navSubscription.unsubscribe();
  }

  public getLastUrl() {
    return this.previousUrl;
  }

在 ngOnInit 的组件中我正在使用:

const lastUrl= this.service.getPreviousUrl();
    if (previous.includes('account')) {
      this.onAccountPage = true;
    }

同时:

  public ngOnDestroy(): void {
    this.form.destroy();
    this.service.unsubscribeNavigation();
  }

上面的代码正在运行,当我来到选项卡内的组件时,我得到最后一个 url,比如说 index.html。问题是当我离开另一个标签时取消订阅 onDestroy 时。当我回到这个选项卡时,我的最后一页仍然是索引,因为订阅不再存在。我该如何克服呢?我想取消订阅,但再次返回标签时我需要该订阅。

【问题讨论】:

    标签: angular angular-router


    【解决方案1】:

    我认为您遇到的问题是服务和组件具有不同的生命周期。如果您使用的是 Angular 10 或 11,您可以让服务实现 OnDestroy 并在那里取消订阅。

    class HistoryService implements OnDestroy {
    
    const url = this.router.url;
        this.Subscription = router.events.subscribe((event) => {
          if (event instanceof NavigationEnd) {
            this.previousUrl = url ;
            url  = event.url;
          }
        });
     
        public getLastUrl() {
          return this.previousUrl;
        }
    
        ngOnDestroy() {
         this.navSubscription.unsubscribe();
        }
         
    }

    当组件被销毁时,我删除了对 this.service.unsubscribeNavigation() 的调用。

    【讨论】:

    • 你是对的,我只是不知道在服务中使用 onDestroy 是否可以:)。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2013-05-18
    • 2017-12-03
    • 2016-10-31
    • 1970-01-01
    • 2020-04-26
    • 2021-06-23
    相关资源
    最近更新 更多