Reputation: 625
I have a page(say page3) which can be accessed from two other pages say page1(parent URL will be parent1 - parent1/page1) and page 2(parent URL will be parent2 - parent2/page2).
Since angular changes the URL by default i want to prevent that URL change only if i am navigating from page2 and i want the URL to change normally when i am navigating from page 1(for all pages with parent url as parent1).
We can do this by
router.navigate('page2',{skipLocationChange: true});
but how can I do this in a common place since I have more pages like page4, page5, page6, etc and I want to prevent location change only for particular pages.
Upvotes: 1
Views: 73
Reputation: 1022
You could subscribe to router events in specific components: https://v2.angular.io/docs/ts/latest/api/router/index/NavigationStart-class.html
In the event handler (after navigation kicks in) you can check what is the parent URL and override it with methods such as history.replaceState()
You could crate global configuration injectable that will have have all rules defined (i.e. which URL to override and which do not). This way you won't need to refactor all router.navigate
but only specify the rule once per component in the component class:
constructor(router: Router, overrideUrlService: overrideUrlService) {
router.events.subscribe(event => {
if(event instanceof NavigationStart) {
//have the override logic in some injectable service
overrideUrlService.checkUrl(event.url);
}
}
});
Upvotes: 1
Reputation: 942
I think a non-obstrusive and clean way would be to wrap router navigation in a helper class (or function) that implements your application-specific needs.
@Injectable
class LocationAwareRouter {
constructor(private router: Router) {
}
public navigate(url: string) {
this.router.navigate(url, { skipLocationChange: this.isLocationChange(url) };
}
private isLocationChange(url: string): boolean {
return /* your fancy URL evaluation here */ ;
}
}
Upvotes: 0