【问题标题】:notification about every change of URL每次更改 URL 的通知
【发布时间】:2020-01-16 12:57:15
【问题描述】:

是否可以获得关于 URL 每次更改的(事件)通知(无需重新加载页面,就像我们可以使用 location.replaceState() 一样)?

更准确地说:我不会更改组件或页面。我只是为将来更改 URL。

UPADATE 不优雅的解决方案:手动触发

var popStateEvent = new PopStateEvent('popstate', { state: state });
dispatchEvent(popStateEvent);

【问题讨论】:

标签: javascript angular routes


【解决方案1】:

您可能需要创建一个可注入到 root 的服务并为其添加一个主题,该主题会在每个组件的每个 onDestroy 中触发。

在服务中:

//imports here
export class TestService {
   pageChange$ = new Subject();
}

在您要触发更改的所有组件中:

//imports
export class TestComponent implements OnDestroy {
//component properties
  constructor(private testSrv: TestService){}
  ngOnDestroy(){
    let notification = 'This page is getting closed';
    testSrv.pageChange$.next(notification);
  }
}

在您想要接收更改的组件中:

//imports
export class HeaderComponent implements OnInit {
//component properties
  constructor(private testSrv: TestService){}
  ngOnInit(){
    let notification = 'This page is getting closed';
    testSrv.pageChange$.subscribe(notification => {
       console.log(notification);
     });
  }
}

这是您可以采取哪些措施来解决问题的总体思路。

更新

如果你只想跟踪 url 的变化,你需要使用Router:

constructor(private router: Router) {}

ngOnInit(){
   this.router.events.subscribe((val) => {
        if(this.router.navigated){
           //do something here
        }
    });
}

【讨论】:

  • 也许我写的不准确,但我没有更改组件或页面。我只是为将来更改 URL。
  • @patrycze 我将答案保留为 as,并在其下方添加了一个更新部分。查看并告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多