传参方式
- routerLink传参
- routerLink
- routerLink && queryParams
- 路由中传参
- navigate传参
- navigateByUrl(待完善)
方式一 routerLink
1 routerLink
routerLink跳转
<!-- 3种方法: 设置参数变量的 值 -->
<a routerLink="/test/1"> 跳转1</a>
<a [routerLink]="['/test/2']"> 跳转2 </a>
<a [routerLink]="['/test',3]"> 跳转3 </a>
对应路由
{ path: 'test/:id', component: PropertyComponent }
接收参数
import { ActivatedRoute } from '@angular/router';
...此处省略一万字...
constructor(private route: ActivatedRoute) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
const id = this.route.snapshot.params['id'];
}
或
import { ActivatedRoute, Params } from '@angular/router';
...此处省略一万字...
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe((params: Params) => {
const id = params['id'];
});
}
2 routerLink && queryParams
<!-- 在html的a标签里直接设置查询参数 key:value,不在路由中配置 -->
<a [routerLink]="['/test']" [queryParams]="{id: 4,title:'新闻详情'}">路由跳转</a>
<!-- 以下不正确 -->
<a [routerLink]="['/test',{queryParams:{id: 4,title:'新闻详情'}}]"> 错误例子 </a>
<a routerLink=["/detail",{queryParams:object}]></a>
对应路由 (路径后没有参数)
{
path: 'test', component: NewsDetailComponent,
}
接收参数
const id = this.route.snapshot.queryParams['id'];
const id = this.route.snapshot.queryParams['title'];
this.route.queryParams.subscribe((params: Params) => {
const id = params['id'];
const title = params['title'];
});
方式二 路由中传参
<a routerLink="/test"> 跳转到详情页 </a>
{
path: 'test',
component: NewsDetailComponent,
data: {
title: '我是详情页1',
subtitle: '我是详情页2'
}
}
获取参数
this.title = this.routeInfo.snapshot.data['title'];
this.title = this.routeInfo.snapshot.data['subtitle'];
方式三 navigate
单个参数
{path: 'news-detail/:id', component: NewsDetailComponent}
方法中调用
this.router.navigate(['/home/news/news-detail/1']);
this.router.navigate(['/home/news/news-detail',1]);
接受参数
import { ActivatedRoute } from '@angular/router';
...此处省略一万字...
constructor(private route: ActivatedRoute) { }
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
const id = this.route.snapshot.params['id'];
console.log('id==>', id);
}
或
import { ActivatedRoute, Params } from '@angular/router';
...此处省略一万字...
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.params.subscribe((params: Params) => {
const id = params['id'];
console.log('id==>', id);
});
}
传多个参数
{
path: 'news-detail', component: NewsDetailComponent,
}
this.router.navigate(['/home/news/news-detail'],
{ queryParams: { 'id': '2' ,title:'详情页'} });
接收
const id = this.route.snapshot.queryParams['id'];
const id = this.route.snapshot.queryParams['title'];
或
this.route.queryParams.subscribe((params: Params) => {
const id = params['id'];
const title = params['title'];
console.log('id==>', id);
console.log('title==>', title);
});
参考
|