Angular 11路由的入门
现在的网络应用是用户友好型的,使用起来很方便。如果你在这里,你可能已经听说过单页应用程序(SPA)。这些应用程序在浏览器中工作,在导航过程中不需要刷新页面。通常情况下,这些页面只需加载一次,而其内容是动态添加的。
简介
SPA的一个例子是Section,用导航内容后面的转发斜线表示。例如,这个平台上的所有文章都位于https://www.section.io/engineering-education/ 。
本教程将引导你完成使用路由器创建Angular应用程序的过程。我们将学习Router出口、导航、路由和路径的基本知识,以生成一个完整的Angular单页应用(SPA)。
为了让你能够跟着这个教程走,掌握Angular的基本知识将是必要的。
开始使用Angular路由器
Angular Router是Angular的一个核心部分,有助于构建一个单页应用程序。它位于@angular/router package 。
它有一个完整的路由库,用于构建多个路由出口。它还支持一些功能,如懒惰加载和用于访问控制的路由守卫等等。
路由和路径
路由是一种对象。在最底层,它们由Angular组件和路径组成,有时还包括redirectTo 。这提供了关于特定路线的更多细节,加上导航时加载的组件。路径是用于定位资源的部分URL。
一个路由的例子。
----------------------------
{
path: '',
component: myDashboardComponent,
},
{
path: 'myPath',
component: MyPathComponent
}
------------------------------
你会注意到,这些路由至少包含一个与它的组件相关的路径。
Angular router-outlet
Router-Outlet是一个来自路由器库的Angular指令,用于插入由路由匹配的组件,在屏幕上显示。
它由RouterModule ,并被添加到模板中,如下图所示。
<router-outlet></router-outlet>
Angular路由守护器
在我们的Web应用程序中,有一些资源我们通常限制它们只能被认证的用户访问。Angular使用路由守卫实现了这一功能。
让我们来看看一个例子。
import { Injectable } from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '@app/core/services';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate
{
constructor(private router: Router, private authService: AuthService) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
{
const user = this.authService.user;
if (user)
{
// user authentication successful
return true;
}
// authentication failed, redirect user to login page
this.router.navigate(['/login']);
return false;
}
}
在这个认证防护脚本中,我们实现了CanActivate ,同时重写了返回布尔值的canActivate() 方法。
如果它返回,并允许访问该组件,否则用户将被重定向到登录页面。
导航指令
通常情况下,我们在HTML中使用<a href='#'>link</a> 标签创建导航链接。在Angular应用程序中,<a> 标签中的href 被替换成routerLink ,如下图所示。
<a routerLink="'/testLink'">my Angular Link</a> //
<a routerLinkActive="'/testLink'">my Angular Link</a> // for active links
运行中的路由
现在我们已经掌握了Angular路由的基本知识,让我们来创建一个单一的应用页面。
第1步:生成一个新的Angular项目
在这一步,让我们通过在终端上运行以下命令来创建一个简单的Angular应用程序,"routing-example"。
ng new routing-example
这时会提示你回答Yes/No ,如下图所示。
// while creating a new angular project, these sets of questions are displayed.
---------------------
? Do you want to enforce stricter type checking and stricter bundle budgets in t
he workspace?
This setting helps improve maintainability and catch bugs ahead of time.
For more information, see https://angular.io/strict No
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? (Use arrow keys)
❯ CSS
SCSS [ https://sass-lang.com/documentation/syntax#scss ]
Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]
Less [ http://lesscss.org ]
Stylus [ https://stylus-lang.com
----------------------
在Angular routing选项中输入Yes ,以便为我们的应用程序生成路由模块。
生成组件
由于我们要用组件来定义路由,让我们通过运行以下命令来生成这些组件。
cd routing-example
ng g component my-dashboard && ng g component student
现在,让我们导航到app.routing-module.ts ,更新路由,如下图所示。
// app.routing-module.ts has the following contents
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{
path: '',
component: MyDashboardCompoent,
},
{
path: 'students',
component: studentComponent,
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes)
],
exports: [
RouterModule
],
})
export class AppRoutingModule { }
这一行,import { Routes, RouterModule } from '@angular/router'; 从router包中导入Routes和RouterModule。然后,我们声明Routes类型的路由常量,这是我们之前导入的。我们已经用各自的组件定义了路径。
在@NgModule()中,我们导入RouterModule ,并通过RouterModule.forRoot(routes) 方法将我们定义的路径传递给它。然后,我们通过导出这个RouterModule ,使其他模块可以访问它。
设置路由器出口
现在我们已经定义了我们的应用路由,现在让我们把路由器出口添加到我们的主应用模板,app.component.html ,如下图所示。
<h4>My First Single page application</h4>
<router-outlet></router-outlet>
接下来,在app. module 中导入app. routing-module 。
--------------------------------------
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { StudentComponent } from './app.component';
import { MyDashboardComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
MyDashboardComponent,
StudentComponent
],
imports: [
---------------
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
你已经走到了这一步?恭喜你,现在让我们为我们的应用程序提供服务。
cd routing-example
ng serve
这将在默认情况下在端口4200 上启动你的应用程序,如果4200 正在使用,则立即启动端口。你现在可以导航到这个路由并测试你的路由。
总结
在本教程中,我们已经讨论了强大的Angular路由工具。我们讨论了如何定义路由并建立一个完整的单页应用程序。
我们讨论了其他Angular路由的概念,如路由器出口、路径和路由。我们还介绍了Angular路由守护的概念,通过看一个用户认证的例子。