2016-09-24 114 views
3

首先調用模板登錄(login.component)。登錄後加載app.componentAngular 2 - 重定向登錄頁面

我的問題是,這可能嗎?我該怎麼做?

Pergunta Editada:

我已經使用了可以激活。對不起,我還在學英語。我想要以下...

bootstrap首先調用app.componet。

@Component({ 
 
    selector: 'my-app', 
 
    template: ` 
 
    \t \t <ul class="sidebar-menu"> 
 
\t \t   <li class="header">Painel</li> 
 
\t \t   <li class="treeview"> 
 
\t \t   <a href="#"><i class="fa fa-link"></i> <span>Loja</span> 
 
\t \t    <span class="pull-right-container"> 
 
\t \t    <i class="fa fa-angle-left pull-right"></i> 
 
\t \t    </span> 
 
\t \t   </a> 
 
\t \t   <ul class="treeview-menu"> 
 
\t \t    <li><a routerLink="/dashboard">Dashboard</a></li> 
 
\t \t   </ul> 
 
\t \t   </li> 
 
\t \t   <li><a routerLink="/users"><i class="fa fa-book"></i> <span>User</span></a></li> 
 
\t \t  </ul> 
 
\t \t  <div class="content-wrapper"> 
 
\t \t   <router-outlet></router-outlet> 
 
\t \t  </div>`, 
 

 
})

export class AppComponent implements OnInit{} 

我想調用app.component之前調用login.component。只有在致電用戶登錄後致電app.component

如果login.component是路由,菜單將被加載,因爲菜單將被加載到<router-outlet></router-outlet>中。

回答

3

使用CanActivate您可以允許用戶訪問頁面,只要它已在路由中激活或重定向到登錄。

import { ModuleWithProviders } from '@angular/core'; 
import { Routes, RouterModule } from '@angular/router'; 
import { CanActivateAuthGuard } from './auth.service' 

import { MyComponent } from './app.component'; 

const routes: Routes = [ 
    { path: '/home', component: MyComponent , canActivate: [CanActivateAuthGuard]}] 

/============/

import { CanActivate, Router } from '@angular/router'; 

@Injectable() 
export class CanActivateAuthGuard implements CanActivate { 

    constructor(private router: Router) {} 
    if (this.authService.isLoggedIn()) { 
     return true; 
    } 
    //Redirect the user before denying them access to this route 
    this.router.navigate(['/login']); 
    return false; 
} 
+0

它的工作!謝謝! –

4

是;這是可能的 - 並且在advanced Routing & Navigation文檔中有詳細描述,特別是在Milestone #4: Route Guards部分。

您需要定義一個CanActivate後衛,然後保護路徑與後衛:

AUTH-guard.service.ts

import { Injectable }  from '@angular/core'; 
import { CanActivate } from '@angular/router'; 

@Injectable() 
export class AuthGuard implements CanActivate { 
    canActivate() { 
    console.log('AuthGuard#canActivate called'); 
    return true; 
    } 
} 

然後使用保護來保護的部分您需要認證的網站:

admin.routing.ts

import { AuthGuard }  from '../auth-guard.service'; 

const adminRoutes: Routes = [ 
    { 
    path: 'admin', 
    component: AdminComponent, 
    canActivate: [AuthGuard], 
    children: [ 
     { 
     path: '', 
     children: [ 
      { path: 'crises', component: ManageCrisesComponent }, 
      { path: 'heroes', component: ManageHeroesComponent }, 
      { path: '', component: AdminDashboardComponent } 
     ], 
     } 
    ] 
    } 
]; 

export const adminRouting: ModuleWithProviders = 
    RouterModule.forChild(adminRoutes); 
+0

它工作!謝謝! –

+0

不客氣,@RenatoSouzadeOliveira - 樂於助人。 :-) –