About Angular 2 Component Communication--A Summary of My Own Points

Posted by inosent1 on Mon, 17 Jun 2019 00:21:08 +0200

Here is a simple record of how you communicate with components in angular 2. Convenient for future use.

I. Ways of Communication between Components

  1. Using Event Emitter, @Output:

  • Scenario: It is possible to communicate between parent and child components. It is commonly used to pass messages from child components to parent components.

  • Step: a. Subcomponent creates EventEmitter object and exposes it with @output; b. parent component listens to the method of @output from subcomponent, and then processes the event.

  • Code:

      // child component
       @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
       @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: I hate posting code. It takes up too much space.

2. Use @ViewChild and @ViewChildren:

  • Scenario: Usually used for parent component to pass information to child component, or parent component to call method of child component;

  • Step: a. Use child components in the parent component; b. Use @ViewChild to get child component objects in the parent component. c. The parent component uses the child component object to manipulate the child component; (pass information or call methods).

  • Code:

 // Subcomponents
   @Component({
     selector: 'app-child2',
     template: '',
     styles: [``]
   })
   export class AppChildComponent2 implements OnInit {
     data = 1;
     ngOnInit(): void {
     }
     getData(): void {
       console.log('TAG' + '---------->>>' + 111);
     }
   }
 // Parent component
       @Component({
         selector: 'app-parent2',
         template: `
           <app-child></app-child>
         `,
         styles: [``]
       })
       export class AppParentComponent2 implements OnInit {
         @ViewChild(AppChildComponent2) child: AppChildComponent2;
         ngOnInit(): void {
           this.child.getData(); // Parent component acquisition subcomponent method
           console.log('TAG'+'---------->>>'+this.child.data);// Parent component obtains child component attributes
         }
       }

3. Use Service service to communicate, that is, two components inject a Service at the same time:

  • Scenario: The two components that need to communicate are not parent-child components or adjacent components; of course, they can also be arbitrary components.

  • Step: a. Create a new service, Component A and Component b inject the service at the same time; b. Component A obtains data from the service, or wants to transfer data from the service; c. Component b obtains data from the service, or wants to transfer data from the service.

  • Code:

       // Component A
       @Component({
         selector: 'app-a',
         template: '',
         styles: [``]
       })
       export class AppComponentA implements OnInit {
         constructor(private message: MessageService) {
         }
         ngOnInit(): void {
           // Component A sends message 3
           this.message.sendMessage(3);
           const b = this.message.getMessage(); // Component A receives messages;
         }
       }
       // Component B
       @Component({
         selector: 'app-b',
         template: `
           <app-a></app-a>
         `,
         styles: [``]
       })
       export class AppComponentB implements OnInit {
         constructor(private message: MessageService) {
         }
         ngOnInit(): void {
           // Component B gets the message
           const a = this.message.getMessage();
           this.message.sendMessage(5);  // Component B sends messages
         }
       }

2. About my own message service module

  1. Scenario: I'm involved in a project that implements the possibility of communication between all components, or that a component needs to communicate with several components.

  2. Design method: (1) Using RxJs, define a service module Message Service, all information registers the service; (2) Where messages need to be sent, invoke the method of the service; (3) Where information needs to be received, invoke the method of receiving information, obtain a Subscription object, and then listen for information; (4) Of course, when each component Destory, it needs to be used. this.subscription.unsubscribe();

  3. Code:

       // Message Specific Service
       @Injectable()
       export class MessageService {
         private subject = new Subject<any>();
         /**
          * content Module for information transmission, similar to broadcasting
          * @param type Type of information sent
          *        1-Your message
          *        2-Your message
          *        3-Your message
          *        4-Your message
          *        5-Your message
          */
         sendMessage(type: number) {
           console.log('TAG' + '---------->>>' + type);
           this.subject.next({type: type});
         }
         /**
          * Send Picture Information
          * @param src:Picture Address
          */
         sendImages(src: string) {
           console.log('AG1' + '---------->>>' + src)
           this.subject.next({url: src});
         }
          /**
          * Clean up the message
          */
         clearMessage() {
           this.subject.next();
         }
          /**
          * Get the news
          * @returns {Observable<any>} Return message listening
          */
         getMessage(): Observable<any> {
           return this.subject.asObservable();
         }
       }
       // Where you use this service, you need to register the Message Service service.
       constructor(private message: MessageService) {
       }
       // Where the news is received;
       public subscription: Subscription;
        ngAfterViewInit(): void {
           this.subscription = this.message.getMessage().subscribe(msg => {
             // Processing your business logic according to msg.
           })
         }
         
         // At the end of the component life cycle, remember to cancel it or you will get a card card.
          ngOnDestroy(): void {
           this.subscription.unsubscribe();
         }
         
         // Call the method of the service and send information.
         send():void {
            this.message.sendImages('www.baidu.com'); // Send Picture Address
            this.message.sendMessage(2);  // Send message
         }

Summary: Message Service here is equivalent to using broadcast mechanism to transmit information between all components; whether it is a number, string or object, it can be transmitted, and the speed of transmission here is also very fast.

Topics: Javascript angular