angular 路由跳转以及传参的几种方式

通过域名跳转的方式获取参数(http://localhost:4200/second/110?productId=1&title=moon)

这种方式配置路由,其中:id是必需的参数,其它的是可配的,写在?后面:

{ path: 'second/:id', component: SecondComponent },

  

通过ts代码跳转:
this.router.navigate(['/second',110], { queryParams: { productId: '1', title: 'moon' } });

  获取【:id】参数的方式:

constructor(private route: ActivatedRoute, private router: Router) { }
var id = this.route.snapshot.paramMap.get('id');

  

在comoent中需要这么获取‘?’ 后面的参数,将参数写在queryParams里
this.router.navigate(['/second',110], { queryParams: { productId: '1', title: 'moon' } });

  

通过ActivatedRoute来获取
  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {

    var id = this.route.snapshot.paramMap.get('id');
    this.name = id;
    console.log(id);
    
    this.route.queryParams.subscribe(param => {
      console.log(param);
      console.log(param.title);
      console.log(param['title']);
      console.log(param.productId);
      console.log(param['productId']);
    });
  }

  


1.this.router.navigate(['user', 1]); 
以根路由为起点跳转

2.this.router.navigate(['user', 1],{relativeTo: route}); 
默认值为根路由,设置后相对当前路由跳转,route是ActivatedRoute的实例,使用需要导入ActivatedRoute

3.this.router.navigate(['user', 1],{ queryParams: { id: 1 } }); 
路由中传参数 /user/1?id=1

4.this.router.navigate(['view', 1], { preserveQueryParams: true }); 
默认值为false,设为true,保留之前路由中的查询参数/user?id=1 to /view?id=1

5.this.router.navigate(['user', 1],{ fragment: 'top' }); 
路由中锚点跳转 /user/1#top

6.this.router.navigate(['/view'], { preserveFragment: true }); 
默认值为false,设为true,保留之前路由中的锚点/user/1#top to /view#top

7.this.router.navigate(['/user',1], { skipLocationChange: true }); 
默认值为false,设为true路由跳转时浏览器中的url是跳转前的路径,但是传入的参数依然有效

8.this.router.navigate(['/user',1], { replaceUrl: true }); 
未设置时默认为true,设置为false路由不会进行跳转

9.页面里url路转写法

<nav>
    <a routerLink="/heroes/{{id}}">点击查看文章详情</a>
    <!--数组格式传参,注是第二种试的routerLink是用[]包括-->
    <a [routerLink]="['/heroes', num]">点击查看文章详情</a>
</nav>

  

原文地址:https://www.cnblogs.com/wolfocme110/p/13457531.html