- 创建路由模块
代码语言:javascript
复制ng generate module app-routing --flat --module=app
- 修改app-routing.module.ts
代码语言:javascript
复制import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
// 引入路由模块
import { Routes, RouterModule } from '@angular/router';
// 引入被路由的组件
import {HomePageComponent} from './scence-station/home-page/home-page.component';
// 定义路由
const routes: Routes = [
// 无路由时默认跳转路由
{ path: '', redirectTo: '/homePage', pathMatch: 'full' },
{ path: 'homePage', component: HomePageComponent },
// 无匹配路由时默认路由
{ path: '**', component: HomePageComponent }
];
@NgModule({
declarations: [],
imports: [
CommonModule,
// 初始化路由模块,监听定义的路由
RouterModule.forRoot(routes)
],
// 导出路由模块
exports: [RouterModule]
})
export class AppRoutingModule { }
- 创建路由出口
代码语言:javascript
复制<router-outlet></router-outlet>
- 创建路由链接
代码语言:javascript
复制<div>
<nav>
<a routerLink="/homePage">HomePage</a>
<!-- 带参数路由 -->
<a routerLink="/details/{{id}}">明细</a>
<a [routerLink]="['/details', id]">明细</a>
</nav>
</div>
- 通过js路由
代码语言:javascript
复制// 引入Router
import { Router } from '@angular/router';
...
// 注入router
constructor( private router: Router) { }
...
// 导航到路由
this.router.navigate(['details', id]);
// 多参数传递
this.router.navigate(['details'], {queryParams: {id: '1',type: 't'}
// 直接通过url导航
this.router.navigateByUrl('details/1');
...
- 从路由中获取参数
代码语言:javascript
复制// 引入Router
import { ActivatedRoute } from '@angular/router';
// 注入ActivatedRoute
constructor( private activatedRoute: ActivatedRoute) {}
...
// 获取参数
this.activatedRoute.queryParams.subscribe(queryParams => {
let id= queryParams.id;
let type= queryParams.type;
});
- 返回上一页
代码语言:javascript
复制import { Location } from '@angular/common';
constructor( private location: Location) {}
goBack(): void {
this.location.back();
}