3
votes

Angular 4.4.0 version Web application (home Page) Page refresh leads to blank screen when canActive() method returns false. (getting url : localhost:4200/#/)

In this case application should navigate to Landing Page(login page) by default. But its not happening in this particular case. Navigation cancel leads to blank screen and works when refresh again.

app.routing.ts

import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';

export const routes: Routes = [
   { path: '', redirectTo: 'pages', pathMatch: 'full' },
   { path: '**', redirectTo: 'pages/landingpage' }
];

 export const routing: ModuleWithProviders = RouterModule.forRoot(routes, { useHash: true });

pages.routing.ts

import { Routes, RouterModule }  from '@angular/router';
import { Pages } from './pages.component';
import { ModuleWithProviders } from '@angular/core';
import { landingPage } from './landingPage/landingPage.component'
import { SignOutService } from '../providers/navlifecycleservices/signout-navservice';
import { SecurityService } from '../providers/security-service/security-service';
import { UserService } from '../providers/user-service/user-service';

export const routes: Routes = [
{
   path: 'landingpage',
   loadChildren: 'app/pages/landingPage/landingPage.module#landingModule'    
 },
{
   path: 'signout',    
   loadChildren: 'app/pages/landingPage/landingPage.module#landingModule',
   canActivate: [SignOutService],
},

{
   path: 'mobile',
   loadChildren: 'app/pages/mobileEnter/mobileEnter.module#mobileModule',
   canActivate: [SecurityService] 
},
{
   path: 'custid',
   loadChildren: 'app/pages/CustomerID/CustomerID.module#CustomerID',
   canActivate: [SecurityService] 
}
{ path: '', redirectTo: 'landingpage', pathMatch: 'full' },
{
  path: 'pages',
  component: Pages,
  children: [
    { path: 'home', loadChildren: 'app/pages/home/home.module#homeModule', canActivate: [UserService] },
    { path: 'accounts', loadChildren: 'app/pages/accountsPage/accountsPage.module#accountsModule', canActivate: [UserService] }

  ]
 },

 ];

 export const routing: ModuleWithProviders = RouterModule.forChild(routes);

canActiveMethod :

canActive(){
    if(this.securityService.isUserLoggedIn() && this.userData.getTokenData()){
        return true;
    }else{
        // this.router.navigate(["/landingpage"]);
        return false;
    }
}
1

1 Answers

1
votes

1. Inside canActive method we should navigate the unauthorized routes to login page.

2. This navigation won't work directly, it should be surrounded by setTimeout.

canActive(){
    if(this.securityService.isUserLoggedIn() && this.userData.getTokenData()){
        return true;
    }else{
        setTimeout(()=> {
             this.router.navigate(["/landingpage"]);
        }, 150);
        return false;
    }
}