angular中的activatedroute和router解释
在angular中,activatedroute
和router
是两个核心的路由服务。他们都提供可以用来检查和操作当前页面路由信息的方法和属性。
activatedroute
activatedroute
是一个保存关于当前路由状态(如路由参数、查询参数以及其他数据)的对象。 它可以让开发人员从路由器中访问路由参数和查询参数。
activatedroute是路由事件数据的载体。 这包括在导航期间收集的静态和动态段以及查询参数、fragment等等。
例如,对于这个路由:
{ path: 'product/:id', component: productdetailcomponent }
通过获取activatedroute
,我们可以轻松地访问id
值:
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属性,该方法采用一个字符串参数并返回一个字符串:
const id = +this.route.snapshot.parammap.get('id');
这里的加号意味着我们将结果转换为数字类型。
另一种访问路由参数的方法是通过订阅parammap
可观察值。subscribe`方法定义给observable带来副作用,就像任何** rxjs **observable一样:
this.route.parammap.subscribe(params => { const id = +params.get('id'); // ... });
这种方式允许动态更改url。(你的组件不需要重新创建。)
router
router
通过向前和向后导航和路由装置提供了一种明显且简单的编程api,同时仍然保留完全配置的强大能力。
路由器是一个抽象的概念,它用于选择输入url,并将其转换为经过测试的规则来获取特定组件。 在angular中,路由器是ngmodule中的引导项之一。 路由器设置可能看起来非常困难,但是一旦了解了基本情况,它们就会感到自然。
基本导航
首先,我们根据常规用法配置routes
数组:
// 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的产品。 每个路径都与对应的组件相关联。
然后,我们在模板或组件类中安排具有相应路由声明的链接:
<!-- 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
指令完成路由导航。现在,当用户点击链接时,路由器会根据路径加载相应的组件并在指令的位置动态渲染该组件。
以上就是angular中的activatedroute和router原理详解的详细内容,更多关于angular activatedroute router的资料请关注代码网其它相关文章!
发表评论