angular子路由使用_使用CanActivate / CanActivateChild Guard保护Angular v2 +路由

本文介绍了如何使用Angular的CanActivate和CanActivateChild Guard来保护应用的路由。通过创建服务和防护,阻止未授权用户访问特定路由,包括整个路由和子路由的保护。文章通过一个简单的示例展示了如何设置和测试身份验证,确保只有登录用户和特定角色的用户可以访问特定区域。
摘要由CSDN通过智能技术生成

angular子路由使用

Protecting routes is something that has to happen in any app with authentication. There will be sections of your applications that you don't want certain users to get to.

在使用身份验证的任何应用中,保护路由都是必须要做的事情。 您的应用程序中有些部分是您不希望某些用户使用的。

We'll be looking at a simple example of how to use Angular router guards to protect an area of our site. While this will be a simple example that you can reference back to, we'll look at more advanced setups in future articles.

我们将看一个简单的示例,说明如何使用Angular路由器防护装置保护我们站点的某个区域。 虽然这是一个简单的示例,您可以参考,但以后的文章中我们将介绍更高级的设置。

In this tutorial, we'll look at how we can use Angular guards to:

在本教程中,我们将研究如何使用Angular防护:

  • Protect an entire section (route)

    保护整个路段(路线)
  • Protect just a part of the app (child routes)

    仅保护应用程序的一部分(子路径)

TLDR:如何创建和使用Angular Guard ( TLDR: How to Create and Use An Angular Guard )

The overall process for protecting Angular routes:

保护Angular路由的整体过程:

  • Create a guard service: ng g guard auth

    创建guard服务: ng g guard auth
  • Create canActivate() or canActivateChild() methods

    创建canActivate()canActivateChild()方法
  • Use the guard when defining routes

    定义路线时请使用防护装置

To create a guard using the Angular CLI, use:

要使用Angular CLI创建防护,请使用:

ng g guard auth

This will create an auth.guard.ts

这将创建一个auth.guard.ts

Here is the generated file:

这是生成的文件:

import {
     Injectable } from '@angular/core';
import {
     CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {
     Observable } from 'rxjs/Observable';
@Injectable()
export class AuthGuard implements CanActivate {
    

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    
      return true;
  }

}

Now we can add in an AuthService that we may have:

现在,我们可以添加一个可能具有的AuthService

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

// import the auth service here
// import { AuthService } from '../core/auth.service';

@Injectable()
export class AuthGuard implements CanActivate {
    

  // add the service we need
  constructor(
    private auth: AuthService,
    private router: Router
  ) {
    }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    

      // handle any redirects if a user isn't authenticated
      if (!this.auth.isLoggedIn) {
    
        // redirect the user
        this.router.navigate(['/login']);
        return false;
      }

      return true;
  }

}

In the canActivate() method, we can do any checks we need to check if a user has access. Return a boolean true/false. Also, this is where you can handle routing users away from a route if they don't have access.

canActivate()方法中,我们可以执行检查用户是否具有访问权限所需的所有检查。 返回布尔值true/false 。 同样,在这里,如果路由用户没有访问权限,则可以处理他们离开路由的情况。

Import this new class into a module so your app knows how to grab it. Then you can use this when defining routes:

将此新类导入模块,以便您的应用知道如何抓取它。 然后,您可以在定义路线时使用它:

// import the newly created AuthGuard

const routes: Routes = [
  {
    
    path: 'account',
    canActivate: [AuthGuard]
  }
];

This will protect the /account route! That's the quick overview on how to use the guards. Let's go a bit more in depth.

这样可以保护/account路线! 这是有关如何使用防护装置的快速概述。 让我们更深入一点。

角路由器守卫 ( The Angular Router Guards )

The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more.

Angular路由器附带一项称为防护功能的功能。 这些为我们提供了控制应用程序流程的方法。 我们可以阻止用户访问某些路线,阻止用户离开路线等等。

We'll only be talking about CanActivate/CanActivateChild in this tutorial, but be aware that these are the available guards:

在本教程中,我们仅讨论CanActivate / CanActivateChild ,但请注意,以下是可用的防护措施:

  • CanActivate: Check if a user has access

    CanActivate :检查用户是否有权访问
  • CanActivateChild: Check if a user has access to any of the child routes

    CanActivateChild :检查用户是否有权访问任何子路由
  • CanDeactivate: Can a user leave a page? For example, they haven't finished editing a post

    CanDeactivate :用户可以离开页面吗? 例如,他们尚未完成帖子的编辑
  • Resolve: Grab data before the route is instantiated

    Resolve :在实例化路由之前获取数据
  • Lazy loading feature modules.

    延迟加载功能模块。
  • CanLoad: Check to see if we can load the routes assets

    CanLoad :检查是否可以加载路线资产

创建示例应用 ( Creating a Sample App )

Our sample app will be a very simple one. We'll use the Angular CLI to create a new Angular app. We'll also create a brand new account and dashboard sections. The requirements:

我们的示例应用程序将是一个非常简单的应用程序。 我们将使用Angular CLI创建一个新的Angular应用。 我们还将创建一个全新的帐户和仪表板部分。 要求:

  • Only logged in users can visit the /account<
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值