angularjs2中的非父子組件的通信
阿新 • • 發佈:2017-08-16
selector spa req tput 關系 lrj sel code ons
[email protected],@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中的非父子組件的通信