2016-08-26 7 views
3

私はルートを持つファイルを持っており、ユーザーがログインをしていないときにアクセスを拒否したいのですが、どうすればいいですか?Angular jsでルートへのアクセスを拒否する2

私のルート

import { provideRouter, RouterConfig } from '@angular/router'; 
import {SymfonyComponent} from './symfony.component'; 
import {Symfony2Component} from './symfony2.component'; 
import {Symfony3Component} from './symfony3.component'; 
import {LoginComponent} from './login.component'; 

const routes: RouterConfig = [ 
    { 
    path: 'all', 
    component: SymfonyComponent 
    }, 

    { 
    path: 'one', 
    component: Symfony2Component 
    }, 
    { 
    path: 'post', 
    component: Symfony3Component 
    }, 
    { 
    path: 'login', 
    component: LoginComponent 
    }, 
]; 

export const appRouterProviders = [ 
    provideRouter(routes) 
]; 
+1

https://angular.io/docs/ts/latest/guide/router.html#!#guards –

答えて

5

あなたは、Angular2のAuthGuardでこれを行うこのAuthGuard documentationをチェックアウトすることができます。ここで

はapp.routes.tsでの使用の例である:あなたいったん

import {Injectable} from '@angular/core'; 
import {CanActivate, Router} from '@angular/router'; 
import {FooAuth} from 'foo'; 
import {Observable} from 'rxjs/Observable'; 

@Injectable() 
export class AuthGuard implements CanActivate { 
constructor(
    private _fooAuth: FooAuth, 
    private _router: Router 
){} 
canActivate() : Observable<boolean>{ 
    return this.isAllowedAccess(); 
} 
private isAllowedAccess() { 
    if(!this._fooAuth.currentSession) { 
     this._router.navigate(['/login']); 
     return Observable.of(false); 
    } 
    return Observable 
     .fromPromise(this._fooAuth.validateSession(this._fooAuth.currentSession)) 
     .mapTo(true) 
     .catch(err => { 
      this._router.navigate(['/login']); 
      return Observable.of(false) 
     }); 
} 

import {AuthGuard} from './app/common/guards/auth.guard'; 
import {HomeComponent} from './app/home/home.component'; 

export const Routes : RouterConfig = [{ 
      path: 'home', 
      component: HomeComponent, 
      canActivate: [AuthGuard] 
     }] 

その後、あなたはガードを作成する必要があり、それは次のようになりますガードを設定すると、canActivate: [AuthGuard]を各ルートに追加することができ、ルートを変更するたびに認証ロジックをチェックします。 (あなたの認証ロジックはログイン認証サービス/モジュールによって異なります)

関連する問題