Angular之路由概述

Angular路由是组件与URL的对应关系,涉及HashLocationStrategy和PathLocationStrategy两种策略。HashLocationStrategy下,浏览器不发送hash部分给服务器;PathLocationStrategy则原样发送URL。路由基本用法包括定义配置、创建根路由模块和添加RouterOutlet。工作流程包括URL解析、匹配激活配置、组件实例化和渲染。
摘要由CSDN通过智能技术生成

是什么

    路由:就是从一个页面跳到另一个页面,当用户输入一个url跳到一个页面,之后用户点击某控件或者输入另一个url之后就跳到另一个页面,实际上,就是页面的跳来跳去。然而,Angular是组件化应用,所以Angular的页面就是组件,跳到页面,其实就是实例化组件渲染到页面上。总的来说,就是url与组件的对应关系。


优缺点

    相对于之前直接配置url的方式相对复杂了一些。


组成

Angular路由有两种路由策略,一种是HashLocationStrategy,另一种是PathLocationStrategy。

HashLocationStrategy

  浏览器向服务器服务器发送请求时不会带上hash部分。例如浏览器发送http://lo

在TypeScript (TS) 和 Angular 中,路由跳转通常通过`RouterModule`模块提供的服务和指令来完成。以下是一个简单的步骤概述: 1. **安装依赖**:首先,确保你在Angular项目中已经安装了`@angular/router`模块,如果还没有,可以运行`ng add @angular/router`。 2. **配置路由模块**:在`app-routing.module.ts`文件中,你需要导入`RouterModule`, `Routes`以及需要的组件。然后定义你的路由规则,如这样: ```typescript import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { HomeComponent } from './home/home.component'; import { AboutComponent } from './about/about.component'; const routes: Routes = [ { path: '', component: HomeComponent }, // 主页 { path: 'about', component: AboutComponent } // 关于页面 ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} ``` 3. **导航到特定路线**:在组件的HTML模板中,你可以使用`routerLink`指令来进行路由跳转,或者在组件内部使用`this.router.navigate`方法: ```html <!-- 使用routerLink --> <a routerLink="/about">关于</a> <!-- 或者在ts中动态跳转 --> <button (click)="goToAbout()">点击去关于</button> ngOnInit() { goToAbout(); } goToAbout() { this.router.navigate(['/about']); } ``` 4. **路由守卫(Optional)**:如果你想控制哪些用户、何时能访问某些路由,可以使用`CanActivate`守卫或其他类型的守卫。
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值