Angualr routerLink 兩種傳參方法及參數的使用

Angualr routerLink 兩種傳參方法及參數的使用:

轉自:https://blog.csdn.net/qq_29483485/article/details/81513013

 

1.路徑:http://localhost:8080/#/product?id=1

<a [routerLink]="['/product']" [queryParams]="{id:1}">詳情</a>
ts獲取查詢參數:

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
 
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
 
 
  private productId : number;
  constructor(private routeInfo:ActivatedRoute, private router: Router) {
 
  }
 
  ngOnInit() {
    //獲取參數值
    this.productId = this.routeInfo.snapshot.queryParams['id'];
  }
 
  //跳轉其他產品頁
  goPage(){
     this.router.navigate(['/product'],{ queryParams: { id: 2 }});
  }
 
}
2. 路徑:http://localhost:8080/#/product/1

<a [routerLink]="['/product',1]">產品</a>
ts獲取查詢參數:

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Params, Router } from "@angular/router";
 
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
 
 
  private productId : number;
  constructor(private routeInfo:ActivatedRoute, private router: Router) {
 
  }
 
  ngOnInit() {
    //獲取參數值
    this.productId = this.routeInfo.snapshot.params['id'];
    //另一種方式參數訂閱
    this.routeInfo.params.subscribe((params: Params) => this.productId = params['id']);
 
  }
 
  //跳轉其他產品頁
  goPage(){
     this.router.navigate(['/product/2']);
  }
 
}
第二種方法需要配置路由:

const routes: Routes =[
    {path: 'product/:id',component: ProductComponent}

————————————————
版權聲明:本文爲CSDN博主「S筱瀟S四維Smile」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/qq_29483485/article/details/81513013

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章