0

Is it possible to get (event) notification about every change of URL (without reloading page, like we can do with use location.replaceState())?

More precisely: I don't change component or page. I just change URL for future.

UPADATE Not elegant solution: manually triggering

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

1 Answers1

1

You may need to create a service injectable to root and add a subject for it that get triggered in every onDestroy for each component.

in a service:

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

in all components where you want to trigger the change:

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

in a component where you want to receive the change:

//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);
     });
  }
}

This is an overall idea of what you might do to solve your issue.

Update

If you want to just track url changes, you need to use Router:

constructor(private router: Router) {}

ngOnInit(){
   this.router.events.subscribe((val) => {
        if(this.router.navigated){
           //do something here
        }
    });
}
MEDZ
  • 2,227
  • 2
  • 14
  • 18
  • Maybe I wrote not precisely but I don't change component or page. I just change URL for future. – patrycze Jan 16 '20 at 13:19
  • @patrycze I've left my answer as as and added an update section below it. Check it out and let me know. – MEDZ Jan 16 '20 at 13:54