2016-05-02 18 views
6

私は角度2と角度のついた最初のステップを踏み出しています。ランディングページを設定する方法は不思議です。角度2のランディングページ

私の目標は、ユーザーがローカルストレージまたはクッキーにトークンを持たないたびにランディングページを表示することです。

私app.component.tsこの

import {Component} from 'angular2/core'; 
import {ROUTER_DIRECTIVES, RouteConfig} from 'angular2/router'; 
import {NavbarComponent} from './navbar.component'; 
import {LoaderComponent} from './loader.component'; 
import {NameListService} from '../shared/index'; 
import {HomeComponent} from '../+home/index'; 
import {AboutComponent} from '../+about/index'; 

@Component({ 
    selector: 'g-app', 
    viewProviders: [NameListService], 
    templateUrl: 'app/components/app.component.html', 
    directives: [ROUTER_DIRECTIVES, NavbarComponent, LoaderComponent] 
}) 
@RouteConfig([ 
    { 
    path: '/', 
    name: 'Home', 
    component: HomeComponent 
    }, 
    { 
    path: '/about', 
    name: 'About', 
    component: AboutComponent 
    } 
]) 
export class AppComponent { 

} 

/自宅のように見え、/私が正しく理解している場合についてもコンポーネントです。今、私はnavbarへのアクセス権を持たない別個のページを持っていたいと思います。彼がログインしていないと、ユーザーはいつも着陸するでしょうか。

誰かが私を助けてくれると助かりました。

これは、私はトークンが利用できないときにあなただけの負荷に特定のルートにリダイレクトすることができますhttps://github.com/mgechev/angular2-seed

+0

おそらくプランカをする方が良いでしょう – thegio

答えて

3

で説明したように、それが許可されている場合、各ルートをチェックするカスタムRouterOutletを作成することができますトークンが存在するかどうかを判定します。ここから適応

import {Directive, Attribute, ElementRef, DynamicComponentLoader} from 'angular2/core'; 
import {Router, RouterOutlet, ComponentInstruction} from 'angular2/router'; 

@Directive({ 
    selector: 'router-outlet' 
}) 
export class LoggedInRouterOutlet extends RouterOutlet { 
    publicRoutes: any; 
    private parentRouter: Router; 

    constructor(_elementRef: ElementRef, _loader: DynamicComponentLoader, 
       _parentRouter: Router, @Attribute('name') nameAttr: string) { 
     super(_elementRef, _loader, _parentRouter, nameAttr); 

     this.parentRouter = _parentRouter; 

    } 

    activate(instruction: ComponentInstruction) { 
     if (!hasToken()) { 
      this.parentRouter.navigateByUrl('/login'); 
     } 
     return super.activate(instruction); 
    } 
} 

https://github.com/auth0-blog/angular2-authentication-sample/blob/master/src/app/LoggedInOutlet.ts


これは、役割やその他のアクセスcontrollsで作業できるように拡張することができ、このような何か。

+1

興味深いです、クラス+1の動作を拡張 –

1

に私のアプリを基づかい定型です。

export class AppComponent { 
    constructor(private router:Router) { 
    if(!hasToken()) { 
     router.navigate(['/LoginForm']); 
    } 
    } 
} 

別の方法としては、ユーザーがそのルートにナビゲートするためにあなたは、ルータ・コンセントをオーバーライドして、活性化に確認することができますhttp://www.captaincodeman.com/2016/03/31/angular2-route-security/

+0

ありがとうございます!それは私が探していたものです – gempir