Angular中路由的基本使用

使用ng 命令之前你的电脑要安装 Angular_CLI,方法网上一搜一大把

  1. 使用ng new ngDemo创建项目
  2. 使用ng g component view/index ng g component view/news ng g component view/aboutsrc/app下创建三个组件

基本路由的配置

  1. 打开src/app/app-routint.module.ts文件,用来配置路由

    1. 引入新建的三个路由

      import { IndexComponent } from './view/index/index.component';
      import { NewComponent } from './view/new/new.component';
      import { AboutComponent } from './view/about/about.component';
      
    2. const routes: Routes = []; 中配置路由

      import { NgModule } from '@angular/core';
      import { Routes, RouterModule } from '@angular/router';
      
      import { IndexComponent } from './view/index/index.component';
      import { NewComponent } from './view/new/new.component';
      import { AboutComponent } from './view/about/about.component';
      import { OtherComponent } from './view/other/other.component';
      
      const routes: Routes = [
        {
          // 这里的路径不需要加/
          path: '',
          component: IndexComponent,
        },
        {
          path: 'about',
          component: AboutComponent,
        },
        {
          path: 'news',
          component: NewComponent,
        },
        {
          path: '**',
          component: OtherComponent,
        },
      ];
      
      @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule],
      })
      export class AppRoutingModule {}
      
      
      <div>
          <h2>这里使用的是 routerLink routerLinkActive</h2>
          <a [routerLink]="[ '/' ]" routerLinkActive="active">首页</a>
          <a [routerLink]="[ '/news' ]" routerLinkActive="active">新闻</a>
          <a [routerLink]="[ '/about' ]" routerLinkActive="active">关于</a>
      </div>
      
      <router-outlet></router-outlet>
      

动态路由的配置

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { IndexComponent } from './view/index/index.component';
import { NewComponent } from './view/new/new.component';
import { AboutComponent } from './view/about/about.component';
import { OtherComponent } from './view/other/other.component';

const routes: Routes = [
  {
    // 这里的路径不需要加/
    path: '',
    component: IndexComponent,
  },
  {
    path: 'about',
    component: AboutComponent,
  },
  {
    // 这里这里,看这里,这里是配置的动态路由
    // 如果访问 /new 不加参数是访问不到的,这个时候可以单独写一个没有参数的路由
    path: 'news/:id',
    component: NewComponent,
  },
  // 如果给的路径不能够匹配别的路由那么会跳转到这里,注意是**
  // 匹配所有进行兜底
  {
    path: '**',
    component: OtherComponent,
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

new.component.ts 这是新闻的组件,用它来做的实验

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { IndexComponent } from './view/index/index.component';
import { NewComponent } from './view/new/new.component';
import { AboutComponent } from './view/about/about.component';
import { OtherComponent } from './view/other/other.component';

const routes: Routes = [
  {
    // 这里的路径不需要加/
    path: '',
    component: IndexComponent,
  },
  {
    path: 'about',
    component: AboutComponent,
  },
  {
    // 这里这里,看这里,这里是配置的动态路由
    // 如果访问 /new 不加参数是访问不到的,这个时候可以单独写一个没有参数的路由
    path: 'news/:id',
    component: NewComponent,
  },
  // 如果给的路径不能够匹配别的路由那么会跳转到这里,注意是**
  // 匹配所有进行兜底
  {
    path: '**',
    component: OtherComponent,
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

子路由的配置

app-routing.module.ts

// 这个是用来配置子路由的
  {
    path: 'admin',
    component: AdminComponent,
    children: [
      {
        path: 'user',
        component: UserComponent,
      },
      {
        path: 'product',
        component: ProductComponent,
      },
    ],
  },

admin.component.html 这个是父组件的文件,在这里配置

<div class="admin">
    <div class="left">
        <!-- 访问子路由的时候需要 父路由/子路由 这样才可以 -->
        <a [routerLink]="[ '/admin/user' ]" routerLinkActive="active">用户</a>
        <a [routerLink]="[ '/admin/product' ]" routerLinkActive="active">产品</a>

    </div>
    <div class="main">
        <router-outlet></router-outlet>
    </div>
</div>

通过配置路由时配置参数

app-routing.module.ts

// 这个是用来配置子路由的
  {
    path: 'admin',
    component: AdminComponent,
    children: [
      {
        path: 'user',
        component: UserComponent,
        // 在这里配置参数
        data: { msg: '我就是张三,张三就是我' },
      },
      {
        path: 'product',
        component: ProductComponent,
      },
    ],
  },

user.component.ts

import { Component, OnInit } from '@angular/core';
// 想要获取路由参数,一定要从这里先引入这个东西
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.less'],
})
export class UserComponent implements OnInit {
  constructor(public route: ActivatedRoute) {}

  ngOnInit(): void {
    // 在这里获取路由配置时设置的 data 中的数据
    this.route.data.subscribe((data) => {
      console.log(data);
    });
  }
}

编程式导航(使用编程式导航要引入Router)

new.component.ts

import { Component, OnInit } from '@angular/core';
// 第一步: 想要获取动态路由传过来的数据必须先引入 ActivatedRoute 这个模块(此模块是用来获取参数用的)
import { ActivatedRoute } from '@angular/router';
// 想要实现编程式导航,需要引入这个模块,并且注入
import { Router } from '@angular/router';

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.less'],
})
export class NewComponent implements OnInit {
  // 第二步:在构造函数中进行注入
  constructor(public route: ActivatedRoute, public router: Router) {
    console.log(this.route);
    // 第三步就是获取啦,各种获取

    // 获取params中的数据

    this.route.params.subscribe((params) => {
      // 在这里就可以获取到 http://localhost:4200/news/222?username=zhangsan#ppppp 中 id对应的值222
      console.log('params中获取的值为:' + params);
      console.log(params.id);
    });

    // 获取QueryString 中的值

    this.route.queryParams.subscribe((qs) => {
      console.log('QueryString中获取的值为:' + qs);
      console.log(qs.username);
    });

    // queryParamMap 中的值,需要使用 get 方法才能获取到

    this.route.queryParamMap.subscribe((qs) => {
      console.log('queryParamMap中获取的值为:' + qs);
      console.log(qs.get('username'));
    });

    // 获取锚点(#)中的值用 fragment

    this.route.fragment.subscribe((qs) => {
      console.log('fragment中获取的值为:' + qs);
    });
  }

  ngOnInit(): void {}

  // 通过编程式导航,跳转到关于页面,并且进行传参数
  goHome(): void {
    // alert('按钮被点击了');
    // 跳转到首页直接 this.router.navigate(['']); ,他就是个空的,代表首页
    // 在数组中加值 this.router.navigate(['about', '12356', '5555']
    // 数组中加了第二个参数是这样的 http://localhost:4200/about/12356?username=zs&pwd=123#testtest
    // 数组再加一个就是这样 http://localhost:4200/about/12356/5555?username=zs&pwd=123#testtest
    this.router.navigate(['about'], {
      // 结果是这样的 http://localhost:4200/about?username=zs&pwd=123
      queryParams: {
        username: 'zs',
        pwd: 123,
      },
      // 结果是这样的 http://localhost:4200/about?username=zs&pwd=123#testtest
      fragment: 'testtest',
      // 是否可以返回上一步,如果是false 就不能回退到上一步了,如果是true 就可以返回上一步,默认true
      replaceUrl: false,
    });
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值