Angular中的ActivatedRoute和Router

Angular中的ActivatedRoute和Router解释

在Angular中,ActivatedRouteRouter是两个核心的路由服务。他们都提供可以用来检查和操作当前页面路由信息的方法和属性。

ActivatedRoute

ActivatedRoute是一个保存关于当前路由状态(如路由参数、查询参数以及其他数据)的对象。 它可以让开发人员从路由器中访问路由参数和查询参数。

ActivatedRoute是路由事件数据的载体。 这包括在导航期间收集的静态和动态段以及查询参数、Fragment等等。

例如,对于这个路由:

typescript 复制代码
{ path: 'product/:id', component: ProductDetailComponent }

通过获取ActivatedRoute,我们可以轻松地访问id值:

typescript 复制代码
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-product-detail',
  template: 'Product Details Component'
})

export class ProductDetailComponent implements OnInit {
  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    const id = +this.route.snapshot.paramMap.get('id');
    // ...
  }
}

在上面的代码示例中,ActivatedRoute通过注入该服务作为构造函数的参数而获取。接下来,我们只需使用快照对象(即this.route.snapshot)就可以快速访问路由参数。要获取参数的特定值,可以使用get方法访问params属性,该方法采用一个字符串参数并返回一个字符串:

typescript 复制代码
const id = +this.route.snapshot.paramMap.get('id');

这里的加号意味着我们将结果转换为数字类型。

另一种访问路由参数的方法是通过订阅paramMap可观察值。subscribe`方法定义给observable带来副作用,就像任何** RxJS **observable一样:

typescript 复制代码
this.route.paramMap.subscribe(params => {
  const id = +params.get('id');
  // ...
});

这种方式允许动态更改URL。(你的组件不需要重新创建。)

Router

Router通过向前和向后导航和路由装置提供了一种明显且简单的编程API,同时仍然保留完全配置的强大能力。

路由器是一个抽象的概念,它用于选择输入URL,并将其转换为经过测试的规则来获取特定组件。 在Angular中,路由器是NgModule中的引导项之一。 路由器设置可能看起来非常困难,但是一旦了解了基本情况,它们就会感到自然。

基本导航

首先,我们根据常规用法配置Routes数组:

typescript 复制代码
// app-routing.module.ts file
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProductListComponent } from './product-list/product-list.component';
import { ProductDetailComponent } from './product-detail/product-detail.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'products', component: ProductListComponent },
  { path: 'products/:id', component: ProductDetailComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

我们设定了三个路由:空路径(主页),产品列表和特定ID的产品。 每个路径都与对应的组件相关联。

然后,我们在模板或组件类中安排具有相应路由声明的链接:

typescript 复制代码
<!-- home.component.html -->
<a routerLink="/">Home</a>
<a routerLink="/products">Product List</a>

<!-- product-list.component.html -->
<ul>
    <li *ngFor="let product of products">
        <a [routerLink]="['/products', product.id]">{{ product.name }}</a>
    </li>
</ul>

<!-- product-detail.component.html -->
<h2>Product Detail</h2>
<p>{{ product }}</p>

在上面的所有代码示例中,我们使用了routerLink指令完成路由导航。现在,当用户点击链接时,路由器会根据路径加载相应的组件并在指令的位置动态渲染该组件。

相关推荐
YGY Webgis糕手之路14 分钟前
OpenLayers 快速入门(九)Extent 介绍
前端·经验分享·笔记·vue·web
患得患失94916 分钟前
【前端】【vueDevTools】使用 vueDevTools 插件并修改默认打开编辑器
前端·编辑器
ReturnTrue86817 分钟前
Vue路由状态持久化方案,优雅实现记住表单历史搜索记录!
前端·vue.js
UncleKyrie22 分钟前
一个浏览器插件帮你查看Figma设计稿代码图片和转码
前端
遂心_24 分钟前
深入解析前后端分离中的 /api 设计:从路由到代理的完整指南
前端·javascript·api
你听得到1134 分钟前
Flutter - 手搓一个日历组件,集成单日选择、日期范围选择、国际化、农历和节气显示
前端·flutter·架构
风清云淡_A41 分钟前
【REACT18.x】CRA+TS+ANTD5.X封装自定义的hooks复用业务功能
前端·react.js
@大迁世界43 分钟前
第7章 React性能优化核心
前端·javascript·react.js·性能优化·前端框架
DownToEarth1 小时前
H5实现获取当前定位
javascript
前端Hardy1 小时前
HTML&CSS:惊艳!科技感爆棚的登录页面代码解析
前端·javascript·html