Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 dynamic routing issue with AOT

I have an app where I need to redirect to different component depending on the URL hit by user, suppose if it's localhost/login it should redirect to route localhost/login/#/login, if localhost/user then localhost/user/#/spreadsheet, this works fine without AOT, but not with AOT, here is my function to get the redirecting route:

export function baseHref() {
    return ((document.location.pathname == '/login/') ? 'login' : ((document.location.pathname.split('/')[3] == 'edit') ? 'edit' : ((window.innerWidth >= 720) ? 'spreadsheet' : 'two-panel')));
}

And here is my route:

export const rootRouterConfig: Routes = [
    // If path is not defined it will redirect to spreadsheet
    { path: '', redirectTo: baseHref, pathMatch: 'full' },
    { path: 'spreadsheet', component: ContactParent },
    { path: 'two-panel', component: ContactParent },
    { path: 'login', component: Login },
    { path: 'login/step1', component: LoginStep1 },
    { path: 'login/step2', component: LoginStep2 },
    { path: 'edit', component: EditSingleContact },
    { path: 'share', component: EditSingleContact }
];

Here it's always redirecting to two-panel route

like image 716
Dheeraj Agrawal Avatar asked Feb 10 '26 15:02

Dheeraj Agrawal


1 Answers

This can be solved by providing routes definition to ROUTES using function factory... (tested on Angular 4.1.2)

Modify your AppModule (app.module.ts):

change RouterModul.forRoot in imports array

imports: [
RouterModule.forRoot(routes)
...

to

RouterModule.forRoot([])

add this two providers in providers array:

... ANALYZE_FOR_ENTRY_COMPONENTS
} from '@angular/core';
...  ROUTES,
} from '@angular/router';
...
providers: [
{provide: ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes},
{provide: ROUTES, multi: true, useFactory: getRoutes},
...

define factory function (at top of the app.module.ts file):

export function getRoutes() {
  return routes;
}

maybe you need also create new file eg: app.routes.ts and put your routes definitions there

export const routes: Routes = [
            {
                path: '',
...

and import it in AppModule (app.module.ts).

import { routes } from './app.routes';
like image 79
Lukáš Pikora Avatar answered Feb 12 '26 14:02

Lukáš Pikora