angular2登录和后续路由

时间:2016-12-06 08:52:47

标签: angular

我有一个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>

2 个答案:

答案 0 :(得分: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)
    ];

添加

<router-outlet></router-outlet>

在app.componet.html

和home.component.html

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

这个想法是应用程序将首先登录,然后登录成功&#39;它将重定向到包含导航栏和其他

的主页

答案 1 :(得分:2)

你需要使用的是一个Guard,这是一个关于如何使用它的简短教程:http://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html这里有一个简单的例子:

使用如下代码创建一个guard(authentication.guard.ts):

@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;
    }
}   

然后在路由配置中指定您的路由依赖于AuthenticationGuard,定义如下:

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

你准备好了!