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

Angular 尝试取消订阅路由订阅时出现问题,angular,angular-router,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 unsub

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

我在职期间:

    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或Angular 11,您可以让服务实现OnDestroy并在那里取消订阅

class HistoryService实现OnDestroy{
const url=this.router.url;
this.Subscription=router.events.subscripte((事件)=>{
if(NavigationEnd的事件实例){
this.previousUrl=url;
url=event.url;
}
});
公共getLastUrl(){
返回此.previousUrl;
}
恩贡德斯特罗(){
此.navSubscription.unsubscribe();
}

}
你是对的,我只是不知道在服务中使用onDestroy是否可以:)。谢谢