Angular 2 - 重定向登录页面

3

首先调用登录模板 (login.component),然后在登录之后加载 app.component

我的问题是,这是否可能?我该怎么做?

编辑后的问题:

我已经使用了 Can Activate。对不起,我还在学习英语。我想要以下内容...

引导程序首先调用 app.component。

@Component({
    selector: 'my-app',
    template: `  
      <ul class="sidebar-menu">
          <li class="header">Painel</li>
          <li class="treeview">
            <a href="#"><i class="fa fa-link"></i> <span>Loja</span>
              <span class="pull-right-container">
                <i class="fa fa-angle-left pull-right"></i>
              </span>
            </a>
            <ul class="treeview-menu">
              <li><a routerLink="/dashboard">Dashboard</a></li>
            </ul>
          </li>
          <li><a routerLink="/users"><i class="fa fa-book"></i> <span>User</span></a></li>
      </ul>
      <div class="content-wrapper">
          <router-outlet></router-outlet>
      </div>`,

})

export class AppComponent implements OnInit{}

在调用app.component之前,我希望先调用login.component。只有在用户登录后才会调用app.component

如果login.component是一个路由,则菜单将被加载,因为菜单将被加载到<router-outlet></router-outlet>中。

2个回答

4
是的,这是可能的 - 并且在高级路由和导航文档中有很好的描述,特别是在Milestone #4: Route Guards部分中。
您需要定义一个CanActivate守卫,然后使用守卫保护路由: auth-guard.service.ts
import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate() {
    console.log('AuthGuard#canActivate called');
    return true;
  }
}

然后使用守卫来保护需要身份验证的站点部分:
admin.routing.ts
import { AuthGuard }      from '../auth-guard.service';

const adminRoutes: Routes = [
  {
    path: 'admin',
    component: AdminComponent,
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: 'crises', component: ManageCrisesComponent },
          { path: 'heroes', component: ManageHeroesComponent },
          { path: '', component: AdminDashboardComponent }
        ],
      }
    ]
  }
];

export const adminRouting: ModuleWithProviders =
    RouterModule.forChild(adminRoutes);

不客气,@RenatoSouzadeOliveira -- 很高兴能帮到你。 :-) - Jan Nielsen

3

使用 CanActivate,您可以允许用户仅在路由已激活或将其重定向到登录页面时才能访问页面。

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CanActivateAuthGuard } from './auth.service'

import { MyComponent } from './app.component';

const routes: Routes = [
    { path: '/home', component: MyComponent , canActivate: [CanActivateAuthGuard]}]

抱歉,我需要您提供具体的需要翻译的内容才能进行翻译。
import { CanActivate, Router } from '@angular/router';

@Injectable()
export class CanActivateAuthGuard implements CanActivate {

  constructor(private router: Router) {}
    if (this.authService.isLoggedIn()) {
        return true;
    }
    //Redirect the user before denying them access to this route
    this.router.navigate(['/login']);
    return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接