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

Problem when trying to unsubscribe from route subscription

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

在职我有:

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

我认为您遇到的问题是服务和组件的生命周期不同。如果您使用 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() 的调用。