angular路由学习

栏目: JavaScript · 发布时间: 4年前

内容简介:最近比较忙,抽空看了angular官网上的先给出一份路由模块配置:在这里routers变量的类型是Routers,其实就是一个Route数组:

最近比较忙,抽空看了angular官网上的 路由与导航 ,其实还是有很多想了解的地方,可惜目前没有时间一一验证学习,只能以后有空再说了,在这里只是记录一下学习是遇到的混淆的点。

路由配置(Route) 路由器(Router) 激活路由(ActivatedRoute) 路由状态(RouterState)

先给出一份路由模块配置:

const routers: Routes = [
  {
    path: '', children: [
      {
        path: '', component: MainComponent, children: [
          {path: 'son', component: SonComponent}
        ]
      },
      {path: 'modal', component: ModalComponent}
    ]
  }
];

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

在这里routers变量的类型是Routers,其实就是一个Route数组:

angular路由学习

所以Route的意思就显而易见了,就是一个简单的路由配置

angular路由学习

Router路由器(我看的时候老是和Route看混),提供导航和操纵 URL 的能力。

angular路由学习

ActivatedRoute包含与当前组件相关的路由信息,可以从上面获取参数,url,父子路由信息等。

angular路由学习

路由状态RouterState,我们都知道路由为一个树,由我们配置的路由信息构建而成,而RouteState就代表当前路由的这棵树,可以通过RouteState获取当前的路由树。 参考链接

这是我按照上边的 路由配置打印的结果,可以看到RouteState最主要的为一个Root属性,类型是ActivatedRoute,一般为AppComponent,而在他的Children属性下一步步可以看到我们的MainCoponemt和SonComponent,我浏览器路由为 http://localhost :4200/son;这说明当前MainComponet和SonComponent,AppComponent都是被路由激活的组件,他们都记录在RouteState这个当前的路由状态上。

angular路由学习

路由快照(Snapshot)

在ActivatedRoute,RouteState等路由信息中,都有一个带有XXXSnapshot字段的属性,这个为快照,也就是当前瞬间的路由信息。

angular路由学习

默认情况下,如果没有访问过其它组件就导航到了同一个组件实例,那么路由器倾向于复用组件实例。如果复用的话,路由的参数可以变化,这也是ActivatedRoute里的参数需要订阅的原因,而快照则是保存每一次路由的信息。

例如我们修改上边son路由,接受一个id参数,一个方法跳转,一个方法显示快照参数:

<p>
  id:{{id}}
</p>
<button (click)="show()">显示id</button>
<button (click)="go()">跳转</button>
id: number;

  constructor(private active: ActivatedRoute, private router: Router) {
  }

  ngOnInit() {
    this.id = +this.active.snapshot.paramMap.get('id');
    console.log('创建');
  }

  show() {
    this.id = +this.active.snapshot.paramMap.get('id');
  }


  go() {
    const id = this.id + 1;
    this.router.navigateByUrl('/son/' + 10);
  }

输入网址 http://localhost :4200/son/9,可以看到id显示9,并且控制台打印了‘创建’:

angular路由学习

点击跳转,路由 变为 http://localhost :4200/son/10,而页面却没有变化,也没有再打印,说明组件进行了复用

angular路由学习

点击显示id,可以看到id变成了10,

angular路由学习

这说明虽然路由复用了,但是路由快照却又是重新的一份,这在仅需要路由瞬时信息即为有效,在路由处理器中通常都是用的路由快照。

总结

其实感觉还有很多想学习的地方,但无奈时间匆忙,所以只能以后再慢慢探究了。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning XSLT 2.0

Beginning XSLT 2.0

Jeni Tennison / Apress / 2005-07-22 / USD 49.99

This is an updated revision of Tennison's "Beginning XSLT", updated for the new revision of the XSLT standard. XSLT is a technology used to transform an XML document with one structure into another ......一起来看看 《Beginning XSLT 2.0》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具