標籤: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中的非父子組件的通訊