2016-12-06 59 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> 

於是就登錄成功我將導航到'Home'

登錄服務:

@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

你需要使用的一員,這裏有一個簡短的教程上什麼如何使用它: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,那麼您也將在登錄頁面中看到導航欄。那是不是很受歡迎? – anshuVersatile