angular使用queryParams在兩個頁面間傳值

1、A組件的數據傳送到B組件中使用
在A組件中

import { Router } from '@angular/router';
 constructor( private router: Router ) { }
 
 this.router.navigate(['system/news(頁面B的路由)'],{
      queryParams: {
        name(隨意起): record.flowName(頁面A中的數據),
        id(隨意起): record.flowMajorKey(頁面A中的數據)
      }
});

B組件中

import { Router, ActivatedRoute } from '@angular/router';
 constructor( private activateInfo: ActivatedRoute ) {};
 
  this.activateInfo.queryParams.subscribe(params =>{
            this.flowMajorKey(B組件的數據)=params.id(A組件中,自己起的名字對應);
            this.flowName(B組件的數據)=params.name(A組件中,自己起的名字對應);
        })

2、類似查看新聞的路由,點擊不同的新聞傳送這條新聞的id過去
A組件中:

 constructor(
    private router: Router) { }
    
 this.router.navigate(['allnews/new', id])

若要寫在HTML頁面

<a [routerLink]="[''allnews/new',id]">新聞1</a>

A1/A2/A3
注意要配A1/A2/A3的路由

  { path: 'new/:id', component: NewComponent },
 constructor(
    private route: ActivatedRoute ) { }
    
    id:any;
    this.route.params.subscribe(params => { this.id= params['id'] })

3、即要傳遞路由path,又要傳遞參數,兩者結合
A組件到B組件,同時還要傳遞一個參數
在A組件中:

  this.router.navigate(['allnews/new', id], {
      queryParams: {
        title: this.title
      }
    })

B組件接收:

constructor(private route: ActivatedRoute ) { }

	//傳遞的是path
    this.route.params.subscribe(params => {
       this.id= params['id']
    });
    //傳遞的是參數
    this.route.queryParams.subscribe(params => {
      this.title=params.title
    })
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章