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

在模板中如下写

<a routerLink="/dashboard" routerLinkActive="active">仪表盘</a>  
 <a routerLink="/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',component:Page1Component},
      {path: 'page2',component:Page2Component},
      {path: '**',component:Page404Component},
    ];

【感受】

以上介绍的内容仅仅是浅显的入门知识,要想深入的学习还是得多敲例子。多读书,多总结。



评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值