路由就是根据不同的URL地址,动态地让根组件挂载其他组件,来实现一个单页面应用

  1. 引入组件,app-routing.module.ts

    import { HomeComponent } from './components/home/home.component';
    import { NewsComponent } from './components/news/news.component';
    import { ProductsComponent } from './components/products/products.component';
    
    
  2. 配置路由

const routes: Routes = [
  {path:'home',component: HomeComponent},
  {path:'news',component: NewsComponent},
  {path:'products',component: ProductsComponent},
  //匹配不到路由的时候加载组件,或者跳转的路由
   {
    path:'',
    redirectTo:'/home',
    pathMatch:'full'
  }
];
  1. 找到根组件模板,配置router-outlet显示动态加载的路由
<h1>

  <!-- 找到根组件模板,配置router-outlet显示动态加载的路由 -->
  <a routerLink="/home" routerLinkActive="active">首页</a>
  <a routerLink="/news" routerLinkActive="active">新闻</a>
  <a routerLink="/products" routerLinkActive="active">商品</a>

</h1>

<router-outlet></router-outlet>

get传值

1、跳转-----news.html

<li *ngFor="let item of list;let key=index">
        <!-- <a href="#">{{key}}-----{{item}}</a> -->
        <a [routerLink]="['/newsContent']" [queryParams]="{aid:key}">{{key}}-----{{item}}</a>
</li>

2、接收---------newsContent.ts

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

constructor(public route:ActivatedRoute) { }

//获取值
 this.route.queryParams.subscribe((data:any)=>{

      console.log(data);
    });

动态路由

  1. 配置动态路由

    {path:'newsContent/:aid',component: NewsContentComponent},
    
  2. 跳转

    <ul>
        <li *ngFor="let item of list;let key=index">
    
            <a [routerLink]="[ '/newsContent', key ]">{{key}}------{{item}}</a>
        </li>
    </ul>
    
  3. 接收

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

constructor(public route:ActivatedRoute) { }

//获取动态路由传值
    this.route.params.subscribe((data:any)=>{
      console.log(data);
    });

动态路由的js跳转

1、引入

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

2、初始化

constructor(public router:Router) { }

3、路由跳转

this.router.navigate(['/newsContent','123']);

//动态跳转
    this.router.navigate(['/home']);

路由get传值js跳转

1、引入NavigationExtras

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

2、定义一个goNews方法执行跳转,用NavigationExtras 配置传参

goNews(){

    //跳转并进行传值
    let queryParams:NavigationExtras={

      queryParams:{'aid':123}
    };

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


  }

父子路由----嵌套路由

1、引入组件---app-routing.module.ts

import { HomeComponent } from './components/home/home.component';
import { WelcomComponent } from './components/home/welcom/welcom.component';
import { SettingComponent } from './components/home/setting/setting.component';

2、路由

const routes: Routes = [
  {
    path:'home',component:HomeComponent,
    children:[
      {path:'welcom',component:WelcomComponent},
      {path:'setting',component:SettingComponent},
      {path:'**',redirectTo:'welcom'}
    ]

  },

3、加载路由----html

<router-outlet></router-outlet>

posted on 2021-09-14 15:16  鬼灯  阅读(43)  评论(0编辑  收藏  举报