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 




10 comments:

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

    ReplyDelete
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. Sibling communication often involves sharing experiences, resolving conflicts, and creating lasting bonds. Best Speeds Internet Effective communication can lead to lifelong friendships and a sense of security within the family dynamic.

    ReplyDelete