關於Angular2組件通訊---本身的一點總結

這裏簡單的記錄本身在angular2中,使用組件通訊的一些方法。方便本身之後的使用。angular2

1、組件之間通訊的方式app

  1. 使用事件通訊(EventEmitter,@Output):
  • 場景:能夠在父子組件之間進行通訊,通常使用在子組件傳遞消息給父組件;
  • 步驟:a. 子組件建立事件EventEmitter對象,使用@output公開出去;b. 父組件監聽子組件@output出來的方法,而後處理事件。
  • 代碼:
// child 組件
       @Component({
         selector: 'app-child',
         template: '',
         styles: [``]
       })
       export class AppChildComponent implements OnInit {
         @Output() onVoted: EventEmitter<any> = new EventEmitter();
         ngOnInit(): void {
           this.onVoted.emit(1);
         }
       }
       // parent 組件
       @Component({
         selector: 'app-parent',
         template: `
           <app-child (onVoted)="onListen($event)"></app-child>
         `,
         styles: [``]
       })
       export class AppParentComponent implements OnInit {
         ngOnInit(): void {
           throw new Error('Method not implemented.');
         }
         onListen(data: any): void {
           console.log('TAG' + '---------->>>' + data);
         }
       }
   ps:很討厭貼代碼,太佔空間了;

2.使用@ViewChild和@ViewChildren:this

  • 場景:通常用於父組件給子組件傳遞信息,或者父組件調用子組件的方法;
  • 步驟:a.父組件裏面使用子組件;b.父組件裏面使用@ViewChild得到子組件對象。 c.父組件使用子組件對象操控子組件;(傳遞信息或者調用方法)。
  • 代碼:
// 子組件
   @Component({
     selector: 'app-child2',
     template: '',
     styles: [``]
   })
   export class AppChildComponent2 implements OnInit {
     data = 1;
     ngOnInit(): void {
     }
     getData(): void {
       console.log('TAG' + '---------->>>' + 111);
     }
   }
// 父組件
       @Component({
         selector: 'app-parent2',
         template: `
           <app-child></app-child>
         `,
         styles: [``]
       })
       export class AppParentComponent2 implements OnInit {
         @ViewChild(AppChildComponent2) child: AppChildComponent2;
         ngOnInit(): void {
           this.child.getData(); // 父組件得到子組件方法
           console.log('TAG'+'---------->>>'+this.child.data);// 父組件得到子組件屬性
         }
       }

3.使用服務Service進行通訊,即:兩個組件同時注入某個服務:url

  • 場景:須要通訊的兩個組件不是父子組件或者不是相鄰組件;固然,也能夠是任意組件。
  • 步驟:a.新建一個服務,組件A和組件B同時注入該服務;b.組件A從服務得到數據,或者想服務傳輸數據;c.組件B從服務得到數據,或者想服務傳輸數據。
  • 代碼:
// 組件A
       @Component({
         selector: 'app-a',
         template: '',
         styles: [``]
       })
       export class AppComponentA implements OnInit {
         constructor(private message: MessageService) {
         }
         ngOnInit(): void {
           // 組件A發送消息3
           this.message.sendMessage(3);
           const b = this.message.getMessage(); // 組件A接收消息;
         }
       }
// 組件B
       @Component({
         selector: 'app-b',
         template: `
           <app-a></app-a>
         `,
         styles: [``]
       })
       export class AppComponentB implements OnInit {
         constructor(private message: MessageService) {
         }
         ngOnInit(): void {
           // 組件B得到消息
           const a = this.message.getMessage();
           this.message.sendMessage(5);  // 組件B發送消息
         }
       }

2、關於我本身的消息服務模塊設計

  1. 場景:我涉及到一個項目,裏面須要實現的是全部組件之間都有可能通訊,或者是一個組件須要給幾個組件通訊。
  2. 設計方式:(1). 使用RxJs,定義一個服務模塊MessageService,全部的信息都註冊該服務;(2). 須要發消息的地方,調用該服務的方法;(3). 須要接受信息的地方使用,調用接受信息的方法,得到一個Subscription對象,而後監聽信息;(4). 固然,在每個組件Destory的時候,須要this.subscription.unsubscribe();
  3. 代碼:
// 消息中專服務
       @Injectable()
       export class MessageService {
         private subject = new Subject<any>();
         /**
          * content模塊裏面進行信息傳輸,相似廣播
          * @param type 發送的信息類型
          *        1-你的信息
          *        2-你的信息
          *        3-你的信息
          *        4-你的信息
          *        5-你的信息
          */
         sendMessage(type: number) {
           console.log('TAG' + '---------->>>' + type);
           this.subject.next({type: type});
         }
         /**
          * 發送圖片信息
          * @param src:圖片地址
          */
         sendImages(src: string) {
           console.log('AG1' + '---------->>>' + src)
           this.subject.next({url: src});
         }
          /**
          * 清理消息
          */
         clearMessage() {
           this.subject.next();
         }
          /**
          * 得到消息
          * @returns {Observable<any>} 返回消息監聽
          */
         getMessage(): Observable<any> {
           return this.subject.asObservable();
         }
       }
// 使用該服務的地方,須要註冊MessageService服務;
       constructor(private message: MessageService) {
       }
       // 消息接受的地方;
       public subscription: Subscription;
        ngAfterViewInit(): void {
           this.subscription = this.message.getMessage().subscribe(msg => {
             // 根據msg,來處理你的業務邏輯。
           })
         }
         
         // 組件生命週期結束的時候,記得註銷一下,否則會卡卡卡卡;
          ngOnDestroy(): void {
           this.subscription.unsubscribe();
         }
         
         // 調用該服務的方法,發送信息;
         send():void {
            this.message.sendImages('www.baidu.com'); // 發送圖片地址
            this.message.sendMessage(2);  // 發送信息消息
         }

總結:這裏的MessageService,就至關於使用廣播機制,在全部的組件之間傳遞信息;無論是數字,字符串,仍是對象都是能夠傳遞的,並且這裏的傳播速度也是很快的。code

相關文章
相關標籤/搜索