Angular2 - 具有登录结构的路由器插座

时间:2016-07-11 18:37:04

标签: angular angular2-routing

我正在构建angular2应用程序,目前我有一个带有导航栏,工具栏和路由器插座的主要内容的主页组件。 我想为登录机制添加一个额外页面,因此如果用户未经过身份验证,则登录页面将显示在整个屏幕中,登录后将导航到具有上述结构的组件。

我该如何管理这个结构?我需要两个路由器插座吗?第一个用于登录和主页之间的导航,另一个用于主页中的主要内容? 还有比两个路由器插座更简单的其他常见结构吗?

3 个答案:

答案 0 :(得分:12)

我通过实现此结构成功实现了此工作流程。 我有两个主要组成部分:

LoginComponent,它的路线是' / login'。 HomeComponent,它的路线是''。 (空路线)。

此外,我为我的HomeComponent设置了一个警卫,检查用户是否在他的canActivate中进行了身份验证。如果不是,我将用户导航到' / login'路由。

然后在我的home组件中,我有以下结构的模板: 工具栏,侧边菜单和路由器插座。

我要做的最后一件事是将其他应用程序路由配置为我的HomeComponent的子路由。 (例如:' / news'是')的儿童路线。

答案 1 :(得分:3)

First of all, I highly recommend utilizing the updated Angular2 router. The newest router includes support for guards which are added to your route configuration to prevent access to certain routes.

After ensuring you have the latest router, you'll need to do several things:

1) Create a top-level component and call this App. This is where your <router-outlet> will go.

2) Create a Login component. This component should include a form for logging in to your application, along with the logic for handling login. Create a route for this component.

3) Create a Home component (you have already done this).

4) Use a guard (new functionality in the latest router) to prevent users from accessing the home component before logging in.

Your code will look something like this (for more info, see: https://medium.com/@blacksonic86/upgrading-to-the-new-angular-2-router-255605d9da26#.n7n1lc5cl)

// auth-guard.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  Router,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

import { AuthService } from './services/auth/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }

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

For more information on guards:

I would also highly suggest reading up on the latest Angular router (the docs have recently been updated): https://angular.io/docs/ts/latest/guide/router.html

答案 2 :(得分:0)

关键是使用子路线

import { RouterModule, Route } from '@angular/router';

const ROUTES: Route[] = [
  { path: 'home', component: HomeComponent },
  { path: 'notes',
    children: [
      { path: '', component: NotesComponent },
      { path: ':id', component: NoteComponent }
    ]
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(ROUTES)
  ]
})

在此处查看更多 the-three-pillars-of-angular-routing

相关问题