Skip to content

Instantly share code, notes, and snippets.

@ReallyLiri
Created July 10, 2019 07:51
Show Gist options
  • Save ReallyLiri/a2b8d3cfdd551191c2092f1c9ed77dd6 to your computer and use it in GitHub Desktop.
Save ReallyLiri/a2b8d3cfdd551191c2092f1c9ed77dd6 to your computer and use it in GitHub Desktop.
Routing Interceptor for Angular7
import { Router, NavigationStart } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';
export function parseQuery(queryString: string) {
const query = {};
const pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (let i = 0; i < pairs.length; i++) {
const pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
export abstract class RoutingInterceptor {
protected constructor(
private router: Router
) {
}
init() {
// this code should be called from a top-level initialization, such as OnInit of AppComponent
this.router.events
.pipe(
filter(event => event instanceof NavigationStart),
pairwise()
)
.subscribe(this.routeChanged());
}
// This is the method you should implement to override routing
protected abstract onRouteChanged(sourceUrl: string, targetUrl: string): string;
private routeChanged(): (eventPair: [NavigationStart, NavigationStart]) => void {
return ([previousEvent, currentEvent]: [NavigationStart, NavigationStart]) => {
const sourceUrl = previousEvent.url;
const targetUrl = currentEvent.url;
const modifiedTargetUrl = this.onRouteChanged(sourceUrl, targetUrl);
if (!modifiedTargetUrl || modifiedTargetUrl === targetUrl) {
return;
}
if (modifiedTargetUrl.indexOf('?') !== -1) {
const split = modifiedTargetUrl.split(('?'));
const query = parseQuery(split[1]);
this.router.navigate([split[0]], {queryParams: query});
} else {
this.router.navigate([modifiedTargetUrl]);
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment