Angular 9 Router Util Service
After upgrading from angularJs (using ui-router)... i found the modern angular router to be dumb.
by nalberg
HTML
<script src="https://unpkg.com/[email protected]/client/shim.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/zone.min.js"></script>
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
<script src="https://unpkg.com/@angular/[email protected]/bundles/core.umd.js"></script>
<script src="https://unpkg.com/@angular/[email protected]/bundles/common.umd.js"></script>
<script src="https://unpkg.com/@angular/[email protected]/bundles/compiler.umd.js"></script>
<script src="https://unpkg.com/@angular/[email protected]/bundles/platform-browser.umd.js"></script>
<script src="https://unpkg.com/@angular/[email protected]/bundles/platform-browser-dynamic.umd.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://unpkg.com/@angular/[email protected]/bundles/router.umd.js"></script>
<my-app></my-app>
TypeScript
let { Component, NgModule, VERSION, Injectable } = ng.core;
const { BrowserModule } = ng.platformBrowser;
const { RouterModule, Route } ng.router;
/***
nav-service.ts
***/
interface IRouteData {
pathArray: any[],
params?: any
}
@Injectable({
providedIn: 'root'
})
class NavService {
constructor(
private router: Router,
) {}
go = (routeName: string, params?: unknown) => {
const routeData = this._getRouteLinkData(routeName, params);
return this.router.navigate(routeData.pathArray, routeData.params);
}
link = (routeName: string, params?: unknown) => {
const routeData = this._getRouteLinkData(routeName, params);
return routeData.pathArray;
}
params = (routeName: string, params?: unknown) => {
const routeData = this._getRouteLinkData(routeName, params);
return routeData.params;
}
_getRouteLinkData = (routeName: string, params?: any): IRouteData => {
const pathArray: any[] = [];
let paramData = params;
const routePaths = this._getRoutePaths(appRoutes, routeName);
_.each(routePaths, (path) => {
if (path.indexOf(':') === 0) {
let value = null;
let field = path.substring(1);
if (params && _.has(params, field)) {
value = params ? params[field] : null;
delete params[field];
}
pathArray.push(value)
} else {
pathArray.push(path);
}
})
return { pathArray, params: paramData };
}
_getRoutePaths = (routes: IRoute[], routeName: string): string[] => {
let path: string[] = [];
const routNameParts = routeName.split('.');
let name = routNameParts.shift();
_.each(routes, (r) => {
if (r.name === name) {
if (r.path) path = path.concat(r.path.split('/'));
if (r.children) path = path.concat(this._getRoutePaths(r.children, routNameParts.join('.')));
return false;
}
return;
});
return path;
}
}
/**
* BELOW IS CODE TO JUST RUN...