Last active
October 4, 2018 09:05
-
-
Save knvpk/975f8952364a06cb4185093ad4db31d8 to your computer and use it in GitHub Desktop.
Generating the Nested Angular Route path with out the Bindings For Analytics Page view event.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Router, NavigationStart, NavigationEnd, NavigationCancel, ActivatedRoute, ActivatedRouteSnapshot} from '@angular/router'; | |
@Component({ | |
selector: 'app-root', | |
templateUrl: './app.component.html', | |
styleUrls: ['./app.component.css'] | |
}) | |
export class AppComponent { | |
title = environment.appName; | |
constructor(private _router: Router, | |
private route: ActivatedRoute) { | |
//Note:: google analytics | |
this._router.events.subscribe( (state) => { | |
if(state instanceof NavigationEnd){ | |
if(ga){ | |
ga('send', 'pageview', { | |
'page': this.generatePath(this.route.snapshot) | |
}); | |
} | |
} | |
}); | |
} | |
/** | |
This function will generate the full nested path with variables rather than values binded | |
Example: users/:user_id/contacts/:contact_id/meetings, | |
generally if ask the activated route URL it will give users/2/contacts/291/meetings | |
**/ | |
private generatePath(route:ActivatedRouteSnapshot){ | |
let paths = []; | |
let childRoute = route; | |
let stopWhile = false; | |
while(!stopWhile){ | |
if(childRoute.children.length){ | |
//Note:: We need to check routeConfig present as well as path is not empty | |
if(childRoute.routeConfig && childRoute.routeConfig.path!=""){ | |
paths.push(childRoute.routeConfig.path); | |
} | |
childRoute = childRoute.children[0] | |
}else{ | |
stopWhile = true; | |
} | |
} | |
return paths.join("/"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment