1

I am facing the issue of a angular2 component "Home" loads 2 times after being redirected from the Login component after user authentication. Please find the details about the components and routing below:-

I have a Login component which is part of the the LOGIN_ROUTER_PROVIDERS. LOGIN_ROUTER_PROVIDERS consits of following routes

const loginRoutes: Routes = [
        { path: '', component: Login },
        { path: 'login', component: Login },
        { path: 'Home', component: Home, pathMatch: 'full' },
        ...HOME_ROUTER_PROVIDERS
    ];
    export const LOGIN_ROUTER_PROVIDERS: ModuleWithProviders =    RouterModule.forRoot(loginRoutes);

My Login component consits of the following method which has the redirection to Home component.

export class Login {
    ...
    public Login(userId, password)
    {
        //authenticate user and on sucessful authentication redirected to Home
         this.router.navigate(['/Home']);
    }

}

After the login/authentication, the home component and some other child level routing components are configured in HOME_ROUTER_PROVIDERS.

HOME_ROUTER_PROVIDERS consits of following routing config

export const HOME_ROUTER_PROVIDERS: Routes = [
    {
        path: 'Home',
        component: Home,
        children: [
            { path: 'WorkbookList/:group', component: WorkbookList },
            { path: 'Workbook/:workbookID', component: Workbook },

            //some other child level routing components route
        ]
    }
];

Home component is as below

export class Home {
        constructor(private _SessionService: SessionService) {
            console.log("In constructor of Home - After Login route");
        }
    }

When the application is executed and on successful authentication, the home component is getting loaded, but on the console I can notice that the statement "In constructor of Home - After Login route" is printed 2 times.

I tried commenting the following 2 lines in the loginRoutes const, but I am getting the error message as "Error: Cannot match any routes: 'Home'"

{ path: 'Home', component: Home, pathMatch: 'full' },
...HOME_ROUTER_PROVIDERS

What is the mistake I am doing here and why the home component loads 2 times?

Should I need to have the loginRoutes and HOME_ROUTER_PROVIDERS in separate NgModule? currently in my design both are residing in the same module i.e. all the components are in same module. In this scenario within the same module how to have 2 different routes and to redirect from one to another? Any ideas?

Krishnan
  • 958
  • 5
  • 21
  • 44

0 Answers0