- 创建路由模块
ng generate module app-routing --flat --module=app
- 修改app-routing.module.ts
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 { }
- 创建路由出口
<router-outlet></router-outlet>
- 创建路由链接
<div>
<nav>
<a routerLink="/homePage">HomePage</a>
<a routerLink="/details/{{id}}">明细</a>
<a [routerLink]="['/details', id]">明细</a>
</nav>
</div>
- 通过js路由
import { Router } from '@angular/router';
...
constructor( private router: Router) { }
...
this.router.navigate(['details', id]);
this.router.navigate(['details'], {queryParams: {id: '1',type: 't'}
this.router.navigateByUrl('details/1');
...
- 从路由中获取参数
import { ActivatedRoute } from '@angular/router';
constructor( private activatedRoute: ActivatedRoute) {}
...
this.activatedRoute.queryParams.subscribe(queryParams => {
let id= queryParams.id;
let type= queryParams.type;
});
- 返回上一页
import { Location } from '@angular/common';
constructor( private location: Location) {}
goBack(): void {
this.location.back();
}