Iam working on angular 6 application with default routing configuration , my question is how I can load route from database after user login this is how my route is now .
const routes: Routes = [
{
path: "",
redirectTo: "dashboard",
pathMatch: "full"
},
{
path: "services",
data: { breadcrumb: "Services" },
component: ServicesComponent,
}]
and the api return the following results
{Path: "/Services", Component: "ServicesComponent"}
{Path: "/Dashboard", Component: "DashboardComponent"}
so how i can overwrite the route with new values
thanks in advance
You can dynamically add routes to your Router
instance whenever and wherever you want.
You need to access routes array and add a new one, like this:
this.router.config.unshift({path: 'myNewRoute', component: ProductListComponent});
Decorator metadata solution:
In your case you need to access Module
metadata, more precisely Decorator
's declarations to search for the component you need. You can check that component's name match with the one received by DB.
let compName = 'ProductListComponent';
let comp: Type<any> = (<any>AppModule).__annotations__[0].declarations.find(comp => {
return comp.name === compName;
});
this.router.config.unshift({path: 'myNewRoute', component: comp});
Obviously feel free to add integrity checks.
Mapping solution
You could more simply make a mapping of db string and component like this:
let mapping = {
'myNewRoute': ProductListComponent,
...
}
Then unshift new route as follows:
this.router.config.unshift({path: 'myNewRoute', component: mapping['myNewRoute']});