Loading...

Angular学习之旅路由router 获取动态路由传值

–>

Angular学习之旅路由router 获取动态路由传值

通过命令来创建带路由的angular项目

ng new routingdemo –routing

进去app文件夹后,app-routing-module.ts文件是配置路由的模块

在app-routing-module.ts

// 引入组件
import { HomeComponent } from './components/home/home.component'
import { NewsComponent } from './components/news/news.component'
import { UserComponent } from './components/user/user.component'
<!--The content below is only a placeholder and can be replaced.-->
<div>
  <h2>根组件</h2>
  <header>
    <ul>
      <li><a routerLink="home">首页</a></li>
      <li><a routerLink="news">新闻</a></li>
      <li><a routerLink="user">用户</a></li>
    </ul>
  </header>
</div>
<!--动态加载的组件显示的地方-->
<router-outlet></router-outlet>
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// 引入组件
import { HomeComponent } from './components/home/home.component'
import { NewsComponent } from './components/news/news.component'
import { UserComponent } from './components/user/user.component'
const routes: Routes = [
  {path:'home',component:HomeComponent},
  {path:'news',component:NewsComponent},
  {path:'user',component:UserComponent},
  // 设置默认路由
  {path:'',redirectTo:'home',pathMatch:'full'},
  // 匹配不到任意路由的时候,加载home
  {path:'**',redirectTo:'home'}

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
<div>
  news
</div>

routerLinkActive=”active”是选中的路由

2.获取动态路由的值

import { Router, ActivatedRoute, Params } from ‘@angular/router’;

constructor(private route: ActivatedRoute) { }

以及正确的写法

this.route.params.subscribe(function (data) {

console.log(data.aid);

})

import { Component, OnInit } from '@angular/core';
//引入ActivatedRoute这个模块
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-newscontent',
  templateUrl: './newscontent.component.html',
  styleUrls: ['./newscontent.component.css']
})
export class NewscontentComponent implements OnInit {

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
    // console.log('获取动态路由')
    // console.log(this.route.params.value.aid);  //错误的写法
    //获取动态路由的传值
    this.route.params.subscribe(function (data) {
      console.log(data.aid);
    })
  }
}

 

本文来源 互联网收集,文章内容系作者个人观点,不代表 本站 对观点赞同或支持。如需转载,请注明文章来源,如您发现有涉嫌抄袭侵权的内容,请联系本站核实处理。

© 版权声明

相关文章