步骤;

一、用到了三个ts文件  subscribe.service.ts 、aa.component.ts(传递参数的组件) 、bb.component.ts(接收参数的组件)

二、实现组件间的传值,不仅仅是父子组件,跨模块的组件也可以实现传值

三、思路: 定义一个服务作为传递参数的媒介注入在要传参的组件的构造器里面,然后对服务里面属性(传参媒介)来赋值和取值实现组件之间的传参。任何组件之间都可以通信了

1)subscribe.service.ts :

import { Injectable } from '@angular/core';
import { ReplaySubject, Subject, Subscription } from 'rxjs';

/**
 *1.定义一个服务,作为传递参数的媒介
 */
@Injectable({
  providedIn: 'root'
})

export class SubscribeService {

  /* 公共模块 */

    //定义一个属性,作为组件之间的传递参数,也可以是一个对象或方法 
    profileInfo: any;

  constructor() {

  }

}

 

2)aa.component.ts:

/**
 *2.传递参数的组件,我这边简单演示,直接就在构造器里面实现传参了
 */ 
@Component({
  selector: 'XXXXXXX',
  templateUrl:"./aa.html",
  styleUrls:["./aa.css"]
})

export class ReportComponent {

  //定义要传递的参数(此处是一个对象,也可以是方法)        
 paramList = [
    { "seleDistance": "北往南-南往北" },
    { "highwayName": "京珠高速" },
    {
      "siteOfData": [
        { "stationName": '清远高岗镇段1' },
        { "stationName": '清远佛岗段2' },
        { "stationName": '清远大庙峡3' },
        { "stationName": '广州九龙湖段4' },
        // { "stationName": '广州民乐镇5' }
      ]
    }
  ];

  //构造器注入PrepService服务    
  constructor(private ps:PrepService){

    //把当前组件参数赋值给Service中的profileInfo属性
    ps.profileInfo = this.paramList;
  }
 }

 

3) bb.component.ts:

/**
 *3.接受参数的组件
 */ 
@Component({
  selector: 'bb',
  templateUrl:"./bb.html",
  styleUrls:["./bb.css"]
})

export class commandComponent {

  //定义参来接收来自service服务profileInfo属性的值
  paramList: any;

  //构造器注入PrepService服务    
  constructor(private ps:PrepService){
    //把PrepService的profileInfo属性的值赋值给requestPrep实现组件的之间的传值
    this.paramList = ps.profileInfo;
  }
 }

 

 posted on 2020-11-29 16:50  楼顶铁板烧  阅读(467)  评论(0编辑  收藏  举报