Angular 授权与未授权主视图

Angular 授权与未授权主视图,angular,Angular,当我的应用程序启动时,我会检查cookies,如果用户获得授权,我会向他展示主组件。如果用户未经授权登录,则需要显示组件 这种逻辑应该在哪里?在app.module.ts中还是在app.component.ts中?如何控制将显示哪个组件?逻辑显示MainComponent,然后如果用户未经授权重定向到LoginComponent不好,用户希望从一开始就看到正确的组件。如果根路由是在RouterModule中硬编码的,我该怎么做 谢谢。 注意:是的,我对Angular 2完全是新手:Roman,A

当我的应用程序启动时,我会检查cookies,如果用户获得授权,我会向他展示主组件。如果用户未经授权登录,则需要显示组件

这种逻辑应该在哪里?在app.module.ts中还是在app.component.ts中?如何控制将显示哪个组件?逻辑显示MainComponent,然后如果用户未经授权重定向到LoginComponent不好,用户希望从一开始就看到正确的组件。如果根路由是在RouterModule中硬编码的,我该怎么做

谢谢。
注意:是的,我对Angular 2完全是新手:

Roman,Angular 2为您提供了CanAtivate方法,您可以使用路由列表配置该方法,以说明用户是否可以访问特定的路由

基本上,您需要像这样配置您的路由

import { AuthGuard } from './shared/auth-guard.service';
const routes: Routes = [
    { path: 'settings', [...other configurations...], canActivate: [AuthGuard] }
   ...other routes...
  ]
因此,每当您尝试访问应用程序的/设置页面时,Angular都会询问AuthGuard您是否可以访问

以下是我对AuthGuard的完整实现,您可能需要进行一些更改:

// Angular
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, NavigationExtras } from '@angular/router';

// Application
import { Session } from './index';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private session: Session, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.session.hasValidAuthToken()) // check if the user can acess the route or not
            return true; // let the user to access the route

        let navigationExtras: NavigationExtras = {
            preserveQueryParams: false,
            queryParams: { url: state.url }
        };

        //if not, redirect to the login route
        this.router.navigate(['/login'], navigationExtras);
        return false;
    }
}
基本上,你需要一个守卫来增加你的路线

您需要设置一个服务,该服务将存储您登录时设置的用户身份验证状态,例如

然后在路由上添加一个守卫,它将检查服务的布尔状态,并允许路由被激活或不被激活。如果警卫返回true,用户可以访问路由,如果不是,则需要将他重定向到您的登录并返回false

让我们很容易做到这一点:

设置auth.service.ts:

别忘了在NGM模块中为您的服务添加提供商

现在,您可以从组件调用服务,并通过使用依赖项注入调用服务来设置已验证状态:

onSubmit() {
  // I set my authenticated state from the service itself after I got the Token
  this.authService.getToken(this.currentUser.email,   this.currentUser.password)
    .subscribe((token) => {
      this.router.navigate(['/dashboard']);  // Route that should be accessed upon login
    });
}
现在在你的路线上加一个守卫

设置auth.guard.ts

使用警卫更新您的路线:

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
不要忘记将保护添加到appModule的提供程序中,并小心提供一次,因为您只需要一个保护实例

providers: [
    AuthGuard
]

注意:因为你有一个非常小的应用程序,你可能会在同一个提供商阵列中同时拥有AuthGuard和你的服务。此外,您不需要为警卫设置共享服务。

您需要从您的尝试中包含一些代码。如果没有代码,我需要有关基本Streegy的帮助来进行尝试。我只有一个包含3个组件和路由的项目。RouterModule.forRoot[{path:,重定向到:'page1',pathMatch:'full'},{path:'page1',组件:Page1Component,canActivate:[AppGuard]},{path:'page2',组件:Page2Componnent},{path:'page3',组件:Page3Componnent},{path:'**',重定向到:'page1'}]这是我的路线。我已经将guard添加到我的默认页面,当guard返回false时,我得到了一个空白屏幕。那么,如何显示登录屏幕呢?在您的案例中,当AuthGuard返回false时,将不会加载目标路由。相反,AppGuard必须将导航重定向到login.component。你已经有登录组件了吗?现在我明白了。谢谢!非常感谢你!现在我有了主意。没问题,很高兴我帮了你。如果你有任何问题,请毫不犹豫地问,如果这对你有帮助,我将非常感谢你能标记为答案:
@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {
  }

  /**
   *  Protects the routes to reach with authentication
   */
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
    if (this.authService.isAuthenticated) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
providers: [
    AuthGuard
]