2016-12-06 7 views
1

私はangular2アプリケーションを持っており、それにログインを追加しています。ログインページが最初に表示され、ログインが成功すると残りのアプリケーションにアクセスできます。angular2ログインとその後のルーティング

しかし、どのようにルーティングを処理するかわかりません。これまでのところ、他のすべてのコンポーネントに加えて、私はcomponent.ts、service、およびhtmlでAuthenticationコンポーネントを作成しました。

私のトップレベルのapp.component.ts:

@Component({ 
    selector: 'my-app', 
    templateUrl: './app/app.component.html', 
    styleUrls:['./app/app.component.css'], 
    directives:[ROUTER_DIRECTIVES, Navbar, Stepper, Cart], 
    providers:[CartService, ProgressService, LoginService] 
}) 

export class AppComponent {} 

路線:

export const routes: RouterConfig = [ 

    { path: '', component: Home }, 
    { path: 'login', component: LoginComponent }, <- I was just trying this 
    { path: 'about', component: About }, 
    { path: 'hall', component: HallComponent }, 
    { path: 'caterer', component: CatererComponent } 

]; 

export const APP_ROUTER_PROVIDERS = [ 
    provideRouter(routes) 
]; 

一番上のアプリのhtml:ログイン成功にそう

<navbar></navbar> 
<router-outlet></router-outlet> 

私はに移動します「ホーム」

ログインサービス:

@Injectable() 
export class LoginService extends BaseService { 

    public errorMessage: string; 

    constructor (http: Http) {super(http);} 

    private _authenticationUrl = this._baseUrl + 'rest-auth/'; // URL to web api 


    login(username: string, password: string) { 

    let body = JSON.stringify({ 
     'username' : username, 
     'password': password 
    }); 

    let headers = new Headers({ 'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers }); 
    this.http.post(this._authenticationUrl + 'login/', body, options) 
        .map(this.extractData) 
        .catch(this.handleError).subscribe(data => this.setToken(data.key), 
                 error => this.errorMessage = <any>error); 
    } 

    setToken(key: string) { 
    console.log(key); 
    localStorage.setItem('auth_token', key); 
    /*do routing here*/ 
    // this.nav.setRoot(StartPage); 

    } 
} 

Home.component.html:

<div class="mdl-grid"> 
    <div class="mdl-cell mdl-cell--12-col"> 

     <p>Home component</p> 
     ... 
<div> 
<hall *ngIf = "makeHallsvisible" [city]="specific_city" [date]="date" (setProduct)="setProduct($event)"></hall> 
<caterer *ngIf = "makeCaterersvisible" [city]="specific_city" (setProduct)="setProduct($event)"></caterer> 
+1

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

+1

角度ルーティングには、この目的のためにガードが追加されました。 @GünterZöchbauerのリンクを確認してください –

+0

確かに!どうもありがとう。 – Nitish

答えて

2

を含むホームにリダイレクトされますされGuardは、ここでの短いチュートリアルですさそれを使用する方法:http://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html、ここでは簡単な例です:あなたのルートに続いて

@Injectable() 
export class AuthenticationGuard implements CanActivate { 
    constructor(private router: Router) { } 

    canActivate(): boolean { 
     if (localStorage.getItem('auth_token')) {   
      return true; 
     } 

     this.router.navigate(['/login']); 
     return false; 
    } 
} 

は、このようなコードでガード(authentication.guard.ts)を作成します。設定だけで、あなたのルートがAuthenticationGuardに依存していることを指定するには、このようにそれを定義します。

{ path: 'caterer', component: CatererComponent, canActivate: [AuthenticationGuard] } 

そして、あなたは行く準備ができています!

2
export const routes: RouterConfig = [ 
     { path: '', component: LoginComponent }, <- always redirect to login 
     { path: 'home', component: Home, 
      children: [ 
       { path: 'about', component: About }, 
       { path: 'hall', component: HallComponent }, 
       { path: 'caterer', component: CatererComponent } 
      ] 
     }, 
     { path: '**', component: LoginComponent }, <- redirect when undefined route 
    ]; 

    export const APP_ROUTER_PROVIDERS = [ 
     provideRouter(routes) 
    ]; 

app.componet.html

内や家庭内

<router-outlet></router-outlet> 

を追加します。 component.html

<navbar></navbar> 
<router-outlet></router-outlet> 

アイデアは、そのアプリが最初のログイン時になると「ログイン成功」の後、それはあなたが使用する必要がどのようなナビゲーションバーおよびその他の

+0

基本的には私のルートをあなたの提案で修正しますか?家庭では<ルーター・アウトレット>ですか?私のhome.component.htmlはかなり大きいです。私はその内容で質問を更新しています。 – Nitish

+0

をapp.componentに配置すると、ログインページにnavbarが表示されます。それはうまくないのですか? – anshuVersatile

関連する問題