angular中的路由跳转

一、概述

  1. 定义:根据不同的URL地址,动态的让根组件挂载其它组件来实现一个单页面应用。

二、安装与配置

  1. 安装项目时ng new 项目名,在询问是否要安装带路由的项目包时,选择Y。其它条件依据情况选择即可。

  2. 带路由项目与不带路由项目的区别:

    • 多了一个路由配置文件app-routing.module.ts

    • app.module.ts文件中引入了路由配置文件,并在imports中注入了。

      import { AppRoutingModule } from './app-routing.module';
      
      imports: [
          BrowserModule,
          AppRoutingModule
        ],
      
    • app.component.html文件中最后部分多了一个标签。用于放置动态加载的组件。

      <router-outlet></router-outlet>
      
    • app-routing.module.ts

    • import { NgModule } from '@angular/core';
      import { RouterModule, Routes } from '@angular/router';
      
      const routes: Routes = [];
      
      @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
      })
      export class AppRoutingModule { }
      
      

三、具体实现

1.a标签进行跳转
  1. 创建组件ng g c home, ng g c news, ng g c product

  2. 将组件引入到根组件中,并在declarations中进行配置。(如果是通过命令生成组件,原则上会配置,但需要检查一下)

    import { NewsComponent } from './components/news/news.component';
    import { HomeComponent } from './components/home/home.component';
    import { ProductComponent } from './components/product/product.component';
    
    
     declarations: [
        AppComponent,
        NewsComponent,
        HomeComponent,
        ProductComponent
      ],
    
  3. 在路由配置文件中引入我们创建的组件,在routes对象中配置路由。

    import { HomeComponent } from './components/home/home.component';
    import { NewsComponent } from './components/news/news.component';
    import { ProductComponent } from './components/product/product.component';
    
    const routes: Routes = [
      { path: 'home', component: HomeComponent },
      { path: 'news', component: NewsComponent },
      { path: 'product', component: ProductComponent },
    ];
    
  4. 配置无路由匹配时,显示首页组件

    const routes: Routes = [
      { path: '**', redirectTo: 'home' },
    ];
    
  5. 通过a标签进行跳转(此时html文件)。[routerLink]属性是用来动态设置跳转的路由,routerLinkActive属性是用来设置路由被选中时的样式,需要在scss或者css文件中声明active类。

    <header class="header">
      <!-- 动态路由 -->
      <a [routerLink]="[ '/home']" routerLinkActive="active">首页</a>
      <!-- 静态路由 -->
      <a routerLink= '/home' routerLinkActive="active">首页</a>
    
      <a [routerLink]="[ '/news']" routerLinkActive="active">新闻</a>
    
      <a [routerLink]="[ '/product']" routerLinkActive="active">商品</a>
    </header>
    <router-outlet></router-outlet>
    
1.1get传值

路由get传值,创建新闻详情组件,并在路由文件app-routing.module.ts中引入。

import { NewsDetailComponent } from './components/news-detail/news-detail.component';
const routes: Routes = [
  { path: 'newsDetail', component: NewsDetailComponent },
];

在新闻页NewsComponenthtml文件中通过[queryParams]属性传递值

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

编写新闻页的ts文件

export class NewsComponent implements OnInit {
  public list: any[] = [];
  constructor() { }

  ngOnInit(): void {
    for (var i = 0; i < 10; i++){
      this.list.push(`这是第${i}条数据`)
    }
  }
}

在新闻详情页NewsDetail组件的ts文件中通过this.route.queryParams.subscribe接收

import { ActivatedRoute } from '@angular/router'

export class NewsDetailComponent implements OnInit {

  constructor(
    public route: ActivatedRoute
  ) {}

  ngOnInit(): void {
// behaviorSubject对象,里面的value是我们传递过来的参数,但是不能直接通过.value获取,需要订阅。
    console.log(this.route.queryParams);
    this.route.queryParams.subscribe((data) => {
      console.log(data);
    })
  }

}
1.2路由传值

app-routing.module.ts中引入并定义,即配置动态路由。

import { NewsDetailComponent } from './components/news-detail/news-detail.component';
// 易错点:当路由中需要携带参数时,需要在冒号前加上斜杠
const routes: Routes = [
  { path: 'newsDetail/:aid', component: NewsDetailComponent },
];

在新闻页NewsComponenthtml文件中通过routerLink的第二个param来传递值

<!-- // 易错点:当路由中需要携带参数时,需要在path末尾加上斜杠 -->
<ul>
  <li *ngFor="let item of list ;let key =index">
    <a [routerLink]="[ '/newsDetail/', item ]">{{key}}----{{item}}</a>
  </li>
</ul>

在新闻详情页NewsDetail组件的ts文件中通过this.route.params.subscribe接收

import { ActivatedRoute } from '@angular/router'

export class NewsDetailComponent implements OnInit {

  constructor(
    public route: ActivatedRoute
  ) {}

  ngOnInit(): void {
// behaviorSubject对象,里面的value是我们传递过来的参数,但是不能直接通过.value获取,需要订阅。
    console.log(this.route.params);
    this.route.params.subscribe(data => console.log(data)
    )
  }

}

2.js跳转(在业务逻辑上实现跳转)
2.1路由传值

(比如登录成功后跳转页面。)

html页面中定义与跳转相关的函数

<button (click)="goProductDetail()">js跳转路由</button><br>

<a [routerLink]="[ '/productDetail/', '1234' ]">跳转到商品详情</a><br>

<button (click)="goHome()">js跳转路由到首页</button><br>

在ts文件中引入router,并在构造函数中注入,然后通过this.router.navigate()进行跳转

import { Component, OnInit } from '@angular/core';
import { Router} from '@angular/router'


export class ProductComponent implements OnInit {

  constructor(
    public router: Router
  ) { }

  ngOnInit(): void {
  }
  goProductDetail() {
    // 普通路由和动态路由都适合
    this.router.navigate(['/productDetail/', '1234'])
  }
  goHome() {
    this.router.navigate(['/home'])
  }
}
2.1get传值

html文件中

<button (click)="goNews()">get传值跳转路由</button>

ts中引入NavigationExtras,实现跳转

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

export class ProductComponent implements OnInit {

  constructor(
    public router: Router
  ) { }

  ngOnInit(): void {
  }
  
  goNews() {
    // 跳转并进行get传值
    // 引入这个NavigationExtras可以更标准一点
    let queryParams: NavigationExtras = {
      queryParams:{'aid':123}
    }
    // 注意此时第要传递的参数是放在中括号外面的。
    this.router.navigate(['/news'], queryParams);
  }
}

3.嵌套路由

app-routing.module.ts中引入,并且给父路由配置子路由。给home路由和product路由配置子路由children

// 引入子路由组件
import { PlistComponent } from './components/product/plist/plist.component';
import { PcateComponent } from './components/product/pcate/pcate.component';
import { WelcomeComponent } from './components/home/welcome/welcome.component';
import { SettingComponent } from './components/home/setting/setting.component';

{
    path: 'home', component: HomeComponent,
    children: [
      { path: 'welcome', component: WelcomeComponent },
      { path: 'setting', component: SettingComponent },
      { path: '**', redirectTo: 'welcome' },
    ]
  },
  { path: 'news', component: NewsComponent },
  {
    path: 'product', component: ProductComponent,
    children: [
      { path: 'list', component: PlistComponent },
      { path: 'cate', component: PcateComponent },
      { path: '**', redirectTo: 'list' },
    ]
  },

在home页面的html文件中,通过a标签进行跳转,并且用router-outlet占位。product页面同。

<div class="content">
  <div class="left">
    <a [routerLink]="[ '/home/welcome']" routerLinkActive="active">欢迎你</a>
    <br>
    <a [routerLink]="[ '/home/setting']" routerLinkActive="active">系统设置</a>
  </div>
  <div class="right">
    <router-outlet></router-outlet>
  </div>
</div>

css样式文件

.content{
  width: 100%;
  height: 500px;
  display: flex;
}
.left{
  width: 200px;
  border-right: 1px solid black;
  height: 500px;
}
.right{
  flex: 1;
}
.active{
  color: red;
}
  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值