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>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM