尝试取消订阅路由订阅时出现问题

时间:2021-04-21 19:51:45

标签: angular angular-router

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

我有:

    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。当我回到这个选项卡时,我的最后一页仍然是索引,因为订阅不再存在。我怎样才能克服它?我想取消订阅,但在返回标签页时我又需要订阅。

1 个答案:

答案 0 :(得分: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() 的调用。