angular 路由使用

  1. 创建路由模块
ng generate module app-routing --flat --module=app
  1. 修改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 { }

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

posted on 2022-04-11 22:39  路过君  阅读(54)  评论(0编辑  收藏  举报

导航