angularjs2中的非父子組件的通訊

來源:互聯網
上載者:User

標籤:info   com   pre   sep   one   his   服務   port   add   

AngualrJs2官方方法是以@Input,@Output來實現組件間的相互傳值,而且組件之間必須父子關係,下面給大家提供一個簡單的方法,實現組件間的傳值,不僅僅是父子組件,跨模組的組件也可以實現傳值

/** *1.定義一個服務,作為傳遞參數的媒介 */@Injectable()export class PrepService{  //定義一個屬性,作為組件之間的傳遞參數,也可以是一個對象或方法      profileInfo: any;    }
/** *2.傳遞參數的組件,我這邊簡單示範,直接就在構造器裡面實現傳參了 */ @Component({  selector: ‘XXXXXXX‘,  templateUrl:"./XXXXXX.html",  styleUrls:["./XXXXXXX.css"]})export class ReportComponent {  //定義要傳遞的參數(此處是一個對象,也可以是方法)          reponsePrep:any ={    name : "臘肉豆皮",    address:"中歐五花肉"  }  //構造器注入PrepService服務      constructor(private ps:PrepService){    //把當前組件參數賦值給PrepService的profileInfo屬性    ps.profileInfo = this.reponsePrep;  } }
/** *3.接受參數的組件 */ @Component({  selector: ‘YYYYYY‘,  templateUrl:"./YYYYYYYY.html",  styleUrls:["./YYYYYYY.css"]})export class commandComponent {  //定義參來接收來自PrepService服務profileInfo屬性的值  requestPrep:any;   //構造器注入PrepService服務      constructor(private ps:PrepService){    //把PrepService的profileInfo屬性的值賦值給requestPrep實現組件的之間的傳值    this.requestPrep = ps.profileInfo;  } }

思路:定義一個服務作為傳遞參數的媒介注入在要傳參的組件的構造器裡面,然後對服務裡面屬性(傳參媒介)來賦值和取值實現組件之間的傳參。

這樣就牛逼了,任何組件之間都可以通訊了,僅供參考,本人也是ng2菜鳥。

angularjs2中的非父子組件的通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.