当前位置: 首页 > 工具软件 > GoAngular > 使用案例 >

angular 路由实现

湛光明
2023-12-01
在angular的可以有一个顶级模块专门负责路由, 然后在根模块AppModule中导入使用。

  1. 首先使用angular cli创建一个路由模块
ng generate module app-routing --flat --module=app


生成的代码:

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

@NgModule({
  imports: [
    CommonModule
  ]
})
export class AppRoutingModule { }

  1. 在路由模块中完成路由表的定义
主要就是配置url的哪个路径导航到具体的某个component

import { HeroesComponent } from './heroes/heroes.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';

const routes: Routes = [
{ path: 'heroes', component: HeroesComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'detail/:id', component: HeroDetailComponent },
{ path: '', redirectTo: '/dashboard', pathMatch: 'full' }
];

上面需要注意的是最后一行, 定义了默认导航的模块。


  1. 在路由模块中初始化路由器
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [
RouterModule
]
})

  1. 在根模块中导入路由模块
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './/app-routing.module';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeroService } from './hero.service';

@NgModule({
declarations: [
AppComponent
//...
],
imports: [
BrowserModule,
AppRoutingModule
//...
],
providers: [HeroService,],
bootstrap: [AppComponent]
})
export class AppModule { }

  1. 在根组件AppComponent中添加 < router-outlet >  , <router-outlet> 就是路由模块的那些组件所要显示的位置
<!--The content below is only a placeholder and can be replaced.-->
<div>
<h1>
{{ title }}
</h1>

<router-outlet></router-outlet>
</div>


  1. 上面主要是通过浏览器地址栏输入对应url来跳转到component, 实际应用中我们还有2种应用
a. 提供UI的链接,类似导航栏, 用户点击时跳转
<nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
</nav>


b. 程序中因为逻辑需要主动跳转,并且动态传参
传参方:
gotoDetails(id: number): void {
this.route.navigateByUrl('/detail/' + id);
}

上面代码路由到某个动态/detail/:id下。即给detail指定的component传参。 类似的html代码为:
<a routerLink="/detail/{{hero.id}}" />

接收方:
const id = +this.route.snapshot.paramMap.get('id');





参考:



 类似资料: