Angular4.x中的路由

本文详细介绍了Angular中的路由配置方法,包括创建带有路由的项目、在路由中传递参数、配置默认路由、动态传值、JS跳转及父子路由等,并提供了丰富的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Angular 命令创建一个配置好路由的项 目

1. 命令创建项目

ng new demo02 –-routing

2. 创建需要的组件

ng g component home

ng g component news

ng g component newscontent

3. 找到 app-routing.module.ts 配置路由

引入组件

import { HomeComponent } from './home/home.component';

import { NewsComponent } from './news/news.component';

import { NewscontentComponent } from './newscontent/newscontent.component';

配置路由

const routes: Routes = [

{path: 'home', component: HomeComponent},

{path: 'news', component: NewsComponent},

{path: 'newscontent/:id', component: NewscontentComponent},

{ path: '', redirectTo: '/home',pathMach:'full' }

]

4. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

<h1>

<a routerLink="/home">首页</a>

<a routerLink="/news">新闻</a>

</h1>

<router-outlet></router-outlet>

二、在路由路径(url)中传递参数

  • 修改路由配置中的path属性,使其可以传递参数   app-routing.module.ts

{path: 'product/:id', component: ProductComponent}

 

  • 修改app.component.html 商品详情页链接

       <a [routerLink]="['/product',1]">商品详情页</a>

  • 修改product.component.ts 接收参数的配置

      import {ActivatedRoute} from '@angular/router';

      constructor(private routeInfo: ActivatedRoute) { }

   ngOnInit() {

       this.productId = this.routeInfo.snapshot.params['id'];

   }

访问localhost:4200 测试

三、在路由配置中传递参数

  • 修改app.component.ts中的toProductDetails()
  1. toProductDetails() {
  2. this.router.navigate(['/product', 2]);
  3. }
  • 把product.component.ts中ngOnInit()从参数快照改为参数订阅
  1. ngOnInit() {
  2. this.routeInfo.params.subscribe((params: Params) => this.productId = params['id']);
  3. }

二、Angula4.x 在已有的项目中配置路由

1. 新建组件

ng g component home

ng g component news

ng g component newscontent

2. 新建 app-routing.module.ts ,app-routing.module.ts 中引入模块

import { NgModule } from '@angular/core';

import { Routes, RouterModule } from '@angular/router';

3. app-routing.module.ts 中引入组件

import { HomeComponent } from './home/home.component';

import { NewsComponent } from './news/news.component';

import { NewscontentComponent } from './newscontent/newscontent.component';

4. app-routing.module.ts 中配置组件

const routes: Routes = [

{path: 'home', component: HomeComponent},

{path: 'news', component: NewsComponent},

{path: 'newscontent/:id', component: NewscontentComponent},

{

path: '',

redirectTo: '/home', pathMatch: 'full'

}

];

4. app-routing.module.ts 中配置模块 暴露模块

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule]

})

export class AppRoutingModule { }

5. 在 app.module.ts 引入刚才定义的路由

import { AppRoutingModule } from './app-routing.module';

6.app.module.ts 里面的 import 注册这个路由模块

imports: [

  BrowserModule,

  AppRoutingModule

]

7.找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

<h1>

<a routerLink="/home">首页</a> <a routerLink="/news">新闻</a>

</h1>

<router-outlet></router-outlet>

三、Angular routerLink 页面跳转 默认跳 转路由

<a routerLink="/home">首页</a>

<a routerLink="/news">新闻</a>

//刚进来路由为空跳转的路由

{

path:'', redirectTo:'home', pathMatch:"full"

}

//匹配不到路由的时候加载的组件 或者跳转的路由 {

path: '**', /*任意的路由*/ // component:HomeComponent redirectTo:'home'

}

四、Angular routerLinkActive 设置 routerLink 默认选中路由

<h1>

<a routerLink="/home" routerLinkActive="active">首页</a>

<a routerLink="/news" routerLinkActive="active">新闻</a>

</h1>

五、路由的动态传值

1.配置动态路由

const routes: Routes = [

{path: 'home', component: HomeComponent}, {path: 'news', component: NewsComponent},

{path: 'newscontent/:id', component: NewscontentComponent}, {

path: '',

redirectTo: '/home',

pathMatch: 'full' }

];

2.获取动态路由的值

import { Router, ActivatedRoute, Params } from '@angular/router';

constructor( private route: ActivatedRoute) {}

ngOnInit() {

console.log(this.route.params);//

this.route.params.subscribe(data=>this.id=data.id);

}

六、路由的 js 跳转

1. 引入

import { Router } from '@angular/router';

2.初 始化

export class HomeComponent implements OnInit {

constructor(private router: Router) {

}

ngOnInit() {

}

goNews(){

// this.router.navigate(['/news', hero.id]);

this.router.navigate(['/news']); }

}

3.路由跳转

this.router.navigate(['/news', hero.id]);

七、路由的 js 跳转 get 传值

1. 引入 NavigationExtras

import { Router ,NavigationExtras,ActivatedRoute} from '@angular/router';

2.定义一个 goNewsContent 方法执行跳转,用 NavigationExtras 配置传参。

goNewsContent(){

let navigationExtras: NavigationExtras = {

queryParams: { 'session_id': '123' },

fragment: 'anchor'

};

this.router.navigate(['/news'],navigationExtras);

}

3.获取 get 传值

constructor(private route: ActivatedRoute) {

console.log(this.route.queryParams);

}

八、父子路由

1. 创建组件引入组件

import { NewsaddComponent } from './components/newsadd/newsadd.component';

import { NewslistComponent } from './components/newslist/newslist.component';

2. 配置路由

{

path: 'news',

component:NewsComponent,

children: [

{ path:'newslist',

component:NewslistComponent

}, {

path:'newsadd',

component:NewsaddComponent

}

] }

3. 父组件中定义 router-outlet

<router-outlet></router-outlet>

Angular4 监听路由URL的变化

 

 

Angular 4检测路由变化,可以使用router.events来监听:

支持的事件类型:

  • NavigationStart:导航开始
  • NavigationEnd:导航结束
  • NavigationCancel:取消导航
  • NavigationError:导航出错
  • RoutesRecoginzed:路由已认证

在判断事件类型需要导入对应的事件类型,如:

import { Router, NavigationStart } from '@angular/router';

监听单一事件

this.router.events

.filter((event) => event instanceof NavigationEnd)  

.subscribe((event:NavigationEnd) => {   

  //do something

});

监听多个事件

constructor(router:Router) {   

 router.events.subscribe(event:Event => {

    if(event instanceof NavigationStart) {

      //    

 } else if(event instanceof NavigationEnd) {

      //    

} else if(event instanceof NavigationCancel) {

      //     

} else if(event instanceof NavigationError) {

      //    

} else if(event instanceof RoutesRecognized) {

      //     

}   

});

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值