$locationChangeStart equivalent in Angular 4
Asked Answered
M

1

6

What is the $locationChangeStart equivalent in Angular 4? I am looking for a handler to track the url changes. I read that there is a location service but I am not sure if I need to use this or look for something here https://angular.io/guide/router.. Any pointers would be really helpful. Thanks!

Update: I want to do this inside a service not a component.

Mikimikihisa answered 12/3, 2018 at 21:41 Comment(0)
Y
8

In Angular there are router events that you can subscribe to:

What you want is the NavigationStart event.

Angular Docs NavigationStart

Here is a nice code example provided as an answer on this StackOverflow question on how to use it properly.

import { Router, ActivatedRoute, NavigationStart } from '@angular/router'; 

export class AppComponent { 
   constructor(public _router: Router, private _activeRoute: ActivatedRoute,    private _location: Location) {
     this.router = _router; 
     this.router.events
         .filter(e => e instanceof   NavigationStart)     
         .pairwise()
         .subscribe((e) => { alert(e); }); 
   }
}
Yttriferous answered 12/3, 2018 at 21:45 Comment(2)
can I use it inside a service?Mikimikihisa
Yes, you can use it in a service. However it is already provided as a service that exposes an observable so it may be a bit redundant to do so if you're intention is to than provide your 'wrapper' service.Yttriferous

© 2022 - 2024 — McMap. All rights reserved.