Friday, September 29, 2017

Communication between Sibling components in Angular

Communication or data exchange between component is pretty common scenario in angular development. We know the property binding and event binding can be implemented for hierarchical communication, i.e to pass data from parent to child component and vice versa. We can implement common service scenario when there is need to communicate among sibling components.

Now, the question is can we implement same solution for parent child communication? The answer is yes, we can because service in angular is singleton in nature. So, it is single source of truth.
Now, let’s implement common service scenario as example.

Step 1) Create multiple component and subscribe common service in target component

Here is example code for that. We will create “SharedService” shortly. Here is code for “Work1” component.

import { Component } from '@angular/core';
import { SharedService } from '../services/SharedService'

@Component({
  selector: 'work1',
  template: `
  <input type="text" name="txtName" [(ngModel)]="name">
  <input type="button" name="Click" value="Click" (click)="refresh()">`
})

export class Work1 {
  name : string;
  constructor(private _sharedService: SharedService ){

  }
  refresh(){
    this._sharedService.publishData(this.name);
  }

}


Here the idea is, when user will click refresh, it will call one function in shared service. The function is responsible to push the data in an observable stream. As soon as service will push the data to stream, the subscriber of the stream will get notification.

Let’s create another component called “Work2”

import { Component } from '@angular/core';
import { SharedService } from '../services/SharedService'

@Component({
  selector: 'work2',
  template: `{{name}}`
})
export class Work2 {
  name : string;

  constructor(private _sharedService : SharedService){

    this._sharedService.name$.subscribe(
      data => {
          this.name = data;
      });
  }
}


Here, you can see that we are subscribing “name” observable in SharedService.  So, when there will be any change of “name” variable then the code within constructor should trigger.

Step2) Create common service.

Now, we will implement the common service which will function as mediator/event publisher in implementation.

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class SharedService {

  private name = new Subject<string>(); 
  name$ = this.name.asObservable();

  publishData(data: string) {
    this.name.next(data);
  }

}

The pushData() function is responsible to push the current data to “name$” observable stream.
So, here is final output 




16 comments:

  1. fully managed it services
    WELCOME TO ANIKA TECH SUPPORT
    Anika Tech Support managed by a team of professionals utilising a combined 20+ years of experience in IT support and Managed IT services Focusing on Proactive support, continuity, growth and development. We are a forward thinking IT Company who support public and private sector using the latest tech as a driving force for our client’s Success.

    ReplyDelete
  2. Thank you. Your blog has solved my problem. Please let us know if you know any limitation using this way on performance.

    ReplyDelete
  3. How much is 1 Dogecoin in USD, you can bitcoin convert from dogecoin, you can change currency form of dollars ,you can count currency in calculator.it is Dollar to convert money in buy anything.

    ReplyDelete
  4. Are you looking for where to buy hemp oil in Australia? Visit Ricks Hemp Oil store to choose from a premium organic range of hemp seed oil products today
    CBD Oil Launceston
    CBD Oil Mackay
    CBD Oil Rockhamptonc

    ReplyDelete
  5. The article unambiguously indicated every one of the positive and negative sides of the issue I'm exceptionally bewildered with the nature of the substance which you have written down. This is a marvelous article! Your article has all the essential data on the individual theme branding companies in chennai

    ReplyDelete
  6. Decent article, thankful for more information Activated carbon manufacturers in tamilnadu The information you gave about has been valuable while analyzing the subject.Activated carbon manufacturing companies in India

    ReplyDelete
  7. Hello @Anonymous, that's actually very good choice, you can keep same codebase for both Android and iOS.Are you interested in App Development With Angular then you must be looking for effective development team then you are at the right place for more details on it please go through the website.visit:

    ReplyDelete
  8. Hello @Anonymous, that's actually very good choiceAs Machine Learning & Artificial Intelligence Experts, we can help you inImplementing complex and highly beneficial algorithms that suits your business model. Our data scientists and AI developers will strategically formulate the algorithms depending on your dataset to overcome your core challenges and forthcoming opportunities.For more info on machine learning development servicesvisit:

    ReplyDelete
  9. We are an Android Application Development Company in the USA, providing android application development services for android devices with experienced android app developers.

    ReplyDelete
  10. Very beautifully explained nice blog buddy .Are you among one of those who are looking for Ios App Development Services then you are at right place we have dedicated development team who are expert in this so what are you waiting for just visit the official website or contact Us.

    ReplyDelete
  11. Very beautifully explained nice blog buddy .Are you among one of those who are looking for Hire Android App Developers then you are at right place we have dedicated development team who are expert in this so what are you waiting for just visit the official website or contact Us.

    ReplyDelete
  12. Very beautifully explained nice blog buddy.If you are looking for Flutter Mobile App Development t then you are at the right place Then you've come to the right place because we have a dedicated development team that is a specialist in this area. So, what are you waiting for? Visit the official website or email us.

    ReplyDelete
  13. Nice information you have shared in blog I am also below sharing few thought on app development please have a look If You are among one of those who are looking for mobile app development company in usa
    then you are at right place we have the robust development team they will develop the app according to your requirements. For more details please visit our website.

    ReplyDelete
  14. HDPE Pipe Fittings - Thanks for your marvelous posting! I really enjoyed reading it. you're a great author. I will be sure to bookmark your blog and will come back very soon.

    ReplyDelete