Angular4应用程序页面刷新导致空白屏幕

时间:2017-09-08 09:49:57

标签: javascript angular angular-ui-router

Angular 4.4.0版本Web应用程序(主页)当canActive()方法返回false时,页面刷新会导致空白屏幕。 (获取网址:localhost:4200 /#/)

在这种情况下,应用程序应默认导航到登录页面(登录页面)。但它并没有发生在这种特殊情况下。导航取消导致空白屏幕,并在再次刷新时工作。

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 个答案:

答案 0 :(得分:0)

1。canActive方法内部,我们应该将未经授权的路线导航到登录页面。

2。此导航无法直接使用,应该被setTimeout包围。

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