angular2 組件之間通訊-使用服務通訊模式 2016.10.27 基於正式版ng2


工作中用到ng2的組件通訊 奈何官方文檔言簡意賅 沒說明白 自己搞明白后 整理后分享下

rxjs 不懂的看這篇文章 講很詳細 http://www.open-open.com/lib/view/open1462525661610.html

以下是服務代碼

 1 import { Injectable } from '@angular/core';
 2 import {Subject}from"rxjs/Subject";
 3 @Injectable()
 4 export class CService {
 5  private outputTitle = new Subject();
 6   //訂閱 
 7 //聲明變量 訂閱Observer
 8   output$ = this.outputTitle.asObservable();
 9 
10   //推送  調用next方法 Subject會向所有已經在其上注冊的Observer多路推送 theValue 
11 
12   UpData(message:any) {
13     this.outputTitle.next(message);
14   }
15 }

以下是子組件中的代碼 節選

 1 import { Component, OnInit ,Input, 
 2 import {CService}from"../shared/corresponded.service";//引入服務  單例模式
 3 
 4 @Component({
 5 //這里一定不要注冊服務提供商 也就是不要在里面聲明
 6   providers: []//不需要提供CService服務
 7    })
 8 export class HomePostsComponent implements OnInit {
 9 
10   constructor(
11               //與父組件的cs服務實例相同 是同一個實例
12               public  _CService:CService) {
13   }
14 
15 //自己業務需要在初始化的時候調用 所以就放在這里了  \
16   ngOnInit() {
17     //發送消息
18 //updata調用next方法 推送數據
19     this._CService.UpData({title:"鈴鐺寵物",ico:""});
20   }
21 
22 }

以下是父組件代碼 節選

 1 import { Component,OnInit,AfterViewChecked,AfterViewInit} from '@angular/core';
 2 //引入服務
 3 import {CService}from"./shared/corresponded.service";
 4 @Component({
 5   //服務供應商 只在父組件使用  子組件不需要
 6   providers: [CService]
 7 })
 8 export class AppComponent implements OnInit,AfterViewChecked,AfterViewInit {
 9 //此處cs 實例和子組件的實例是一樣的  都是同一個實例 
10   constructor(private CS:CService) {
11 
12   }
13 
14   //在ngAfterViewChecked每次做完組件視圖和子視圖的變更檢測之后調用。 會執行多次
15   //ngAfterViewInit初始化完組件視圖及其子視圖之后調用。只調用一次
16   //訂閱組件信息  只寫了接收 沒寫發送 道理是一樣的 
17   ngAfterViewInit() {
18     let that = this;
19     console.log("ngAfterViewInit");
20     this.CS.output$.subscribe((value:any)=> {
21       console.log(value);
22       that.title = value.title;
23       that.ico = value.ico;
24     })
25   }
26 
27   
28 }

整個通信流程 核心就是單例  只有一個服務的實例  目前就這么多了  不明白的留言交流吧 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM