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