路由的基本认识

时间:2018-09-19 10:00:54   收藏:0   阅读:242

一、学单词:angular路由中涉及到很多新单词词汇

单词说明使用场景
Routes 配置路由,保存URL对应的组件,以及在哪个RouterOutlet中展现  
RouterOutlet 在html中标记挂载路由的占位容器  
Router 在ts文件中负责跳转路由操作 Router.navigate(["/xxx"]),Router.navigateByUrl("/xxx")
routerLink 在html中使用页面跳转 <a [routerLink]="[‘/xx‘]"
routerLinkActive 表示当前激活路由的样式 routerLinkActive="active"
ActivedRoute 获取当前激活路由的参数, 这个是一个类,要实例化,使用实例化后的对象.params,xx.queryParams
redirectTo 重定向 redirectTo="/路径"
useHash 使用哈希值展现 {useHash:true}
pathMatch 完全匹配 pathMatch:"full"

二、实现一个简单的路由

三、一个简单的路由案例代码,使用了redirectTo做重定向

```javascript
import { NgModule } from ‘@angular/core‘;
import { Routes, RouterModule } from ‘@angular/router‘;
import {Page1Component} from "app/page1/page1.component";
import {Page2Component} from "app/page2/page2.component";

const routes : Routes = [
  {path: ‘‘,redirectTo:"/page1",pathMatch:"full"},
  {path: ‘page1‘,component:Page1Component},
  {path: ‘page2‘,component:Page2Component},
];

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

```
```html
<div class="container" >
<div class="row">
    <div class="col-md-2">
        <ul class="list-group">
            <li class="list-group-item"><a [routerLink]="[‘/page1‘]">列表一</a></li>
            <li class="list-group-item"><a [routerLink]="[‘/page2‘]">列表二</a></li>
        </ul>
    </div>
    <div class="col-md-10" >
        <router-outlet></router-outlet>
    </div>
</div>

``` ### 四、添加404页面 >如果用户输入的`url`地址不正确,或者输入的地址不存在跳转到指定的路径,使用"**"去匹配,路由会先从上面匹配,如果匹配不成功就会往下匹配

```javascript
const routes : Routes = [
  {path: ‘‘,redirectTo:"/page1",pathMatch:"full"},
  {path: ‘page1‘,component:Page1Component},
  {path: ‘page2‘,component:Page2Component},
  {path: ‘**‘,component:Page404Component},
];
```

五、在TS文件中通过事件绑定跳转页面实现切换路由

在ts文件中实现路由的跳转有两种方式:本人建议用第一种,跟html页面中保持一致

六、实现选择当前路由高亮显示

七、路由实现两个组件之间切换传递参数,主要有两种方式

八、配置子路由

九、辅助路由(兄弟路由)就是一个页面中使用多个路由插座<router-outlet></<router-outlet>

使用方式:

原文:https://www.cnblogs.com/dreamingbaobei/p/9672717.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!