Angular4--路由基础
【背景】 最近在学习Angular,迫不及待的想把学习到的内容跟大家分享。 【内容】 1.实现一个简单的路由 (1)使用angular-cli创建一个带路由的项目 ng new 项目名称 --routing
会多创建一个app-routing.module.ts文件代码如下
import { NgModule } from '@angular/core'; import { Routes,RouterModule } from '@angular/router'; const routes: Routes = [ { path: '',children: [] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)],exports: [RouterModule],providers: [] }) export class AppRoutingModule { }
2.简要介绍路由的五个对象 Routes 必备:path,component 这里的path不要加/,为了能够灵活运用绝对路径和相对路径 通配符**,一般放在最后面,作为没匹配到特殊路由的默认路由。 匹配顺序:先匹配者优先 const routes : Routes = [ {path: 'page1',component:Page1Component},{path: 'page2',component:Page2Component},];
RouterLink(指令),用于模板中跳转路由 路由加/,说明是跟路由 路由加./,说明是子路由 input <a routerLink="/dashboard" routerLinkActive="active">仪表盘</a> <a routerLink="/heroes" routerLinkActive="active">英雄列表</a> input type="button" value="英雄列表" (click)="toProductDetails()" > <router-outlet></router-outlet>
注意,锚标签中的[routerLink]绑定。我们把RouterLink指令(ROUTER_DIRECTIVES中的另一个指令)绑定到一个字符串。 它将告诉路由器,当用户点击这个链接时,应该导航到哪里。 Router 在模板中如下写 <arouterLink="/dashboard"routerLinkActive="active">仪表盘</a> <arouterLink="/heroes"routerLinkActive="active">英雄列表</a> <input type="button" value="英雄列表" (click)="toProductDetails()"> <router-outlet></router-outlet>
在app.component.ts中如下写
constructor(private router:Router){ } toProductDetails(){ this.router.navigate(['/product']); }
ActivatedRoute 在路由中传递数据时就用到了ActivatedRoute对象 (1)在查询参数中传递数据 /product?id& name=2 => ActivatedRoute.queryParams[id]
(2)在路由路径中传递数据 {path:/product/:id} => /product/1 => ActivatedRoute.params[id]
(3)在路由配置中传递数据
3.添加404页面
如果用户输入的url地址不正确,或者输入的地址不存在跳转到指定的路径,使用”**”去匹配,路由会先从上面匹配,如果匹配不成功就会往下匹配
const routes : Routes = [ {path: 'page1',{path: '**',component:Page404Component},]; 【感受】 以上介绍的内容仅仅是浅显的入门知识,要想深入的学习还是得多敲例子。多读书,多总结。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |