Angular路由在标签里传参

(情景:点击news.component.html里的路由标签跳转到详情页(news-detail.component.html),并把参数传过去)

1.在app-routing.module.ts里配置路由:

............此处省略
const routes: Routes = [
    // 刚进来为空的话就跳转到home路由
    {
      path:'',
      redirectTo:'home',
      pathMatch:'full'
    },
    {
      path:'home',
      component: HomeComponent,
      
    },
    {
    	
      path:'news',
      component: NewsComponent,
      
    },
    {
      path:'user',
      component: UserComponent,
      children:[]
    },
    {
    	//路由传参(加上冒号),谁要接收参数谁就在在路由配置里带上参数(形参)
        path:'news-detail/:id',
        component: NewsDetailComponent
    },

// 匹配不到路径的时候默认显示home页面
{
  path:'**',
  //redirectTo:'home',
  component: HomeComponent,
  
 
},

];

2.news.component.html:

<li>
	//路由跳转的时候news页面把参数1传递给news-detail页面
      <a [routerLink]="['/news-detail/1']">
        前往详情页1
      </a>
    </li>
    <li>
      <a [routerLink]="['/news-detail/2']">
        前往详情页2
      </a>
    </li>
    <li>
      <a [routerLink]="['/news-detail/3']">
        前往详情页3
      </a>
    </li>

3.在news-detail.component.ts里引入ActivatedRoute
(谁要获取路由参数就在谁那里引入ActivatedRoute)

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

4.在构造器里注入ActivatedRoute:

constructor( private route: ActivatedRoute ){}

5.通过this.route.params获取路由参数:

ngOnInit(){
	//这里的route是构造器里注入声明的route,
	//console.log(this.route.params)
	//不能这样获取id
	//console.log(this.route.params.value.id)
	//获取的是observers对象(不能直接使用),通过subscribe()获取
	this.route.params.subscribe(function(data){
			console.log(data)
	}
		//data=>this.id=data.id
	);
}

猜你喜欢

转载自blog.csdn.net/qq_43579525/article/details/84261809