angular中路由跳轉並傳值四種方式


一、路由傳值

  步驟1 路由傳遞參數 注意 一定是要傳遞 索引值 let key = index 這種情況是在瀏覽器中可以顯示對應的參數 這種的是問號 localhost:8080/news?id=2&name=xiaoming

<div class="z-shebei-box1 x-mysh-p"  style="width: 100%;" *ngFor='let item of deviceInfo.list ;let key = index;'>
     <a [routerLink]="['/devicepay']" [queryParams]="{id:key}">
         <ul>
           <li>{{item}}</li>
         </ul>
     </a>
 </div> 

步驟2 接收傳過來的參數 注意:接收時通過 queryParams 進行接收

首先:引入 import {ActivatedRoute} from '@angular/router'
再:聲明:constructor(public route:ActivatedRoute) { }
接收: // 接收傳過來的值
    this.route.queryParams.subscribe((res)=>{
      console.log(res)
    })

 

二、動態路由傳值這種情況是在瀏覽器中可以顯示對應的參數 這種的是斜桿 localhost:8080/news/id=2&name=xiaoming

步驟1 在路由中進行配置

 

{ path: 'devicepay/:id',component:DevicepayComponent},

 

步驟2 在html界面中進行跳轉

<div class="z-shebei-box1 x-mysh-p"  style="width: 100%;" *ngFor='let item of deviceInfo.list ;let key = index;'>
      <a [routerLink]="['/devicepay/',key]">
           <ul>
            <li>{{item}}</li>
         </ul>
      </a>
  </div>

 

步驟3 在另一界面中接收傳過來的參數 注意 :動態路由接收時使用的是 params

引入 import {ActivatedRoute} from '@angular/router'
再:聲明:constructor(public route:ActivatedRoute) { }
接收: // 接收傳過來的值
    this.route.params.subscribe((res)=>{
      console.log(res)
    })

 

三、動態js進行跳轉 主要在方法對象中使用

步驟1 html 中 注意里面傳入的key值是 循環中 獲取的索引值

<button (click)='gotoDevicePay(key)'>跳轉到支付界面</button>

步驟2 路由文件中寫入的格式如下

{ path: 'devicepay',component:DevicepayComponent},

 

步驟3 js中 進行路由跳轉

//先引入
import { Router} from '@angular/router'
//再聲明
constructor( public router:Router) { }

//定義點擊事件
gotoDevicePay(key):void{
    //跳轉路徑 實現的是動態跳轉數據
    this.router.navigate(['/devicepay/'],{queryParams:{id:key}})
  }

 

四、通過get方式可以傳入多個參數到下一界面

步驟1 引入 NavigationExtras

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

 

步驟2. 定義一個 goNewsContent 方法執行跳轉 , 用 NavigationExtras

goNewsContent(){
    let navigationExtras: NavigationExtras = {
    queryParams: { 'session_id': '123' },
    fragment: 'anchor'
    };
    this.router.navigate(['/news'],navigationExtras);
}

步驟3. 獲取 傳過來的值

constructor(private route: ActivatedRoute) {
   console.log(this.route.queryParams);
}

 


免責聲明!

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



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