Search code examples
angularrxjsangular-servicesbehaviorsubjectsubject-observer

Angular: Share data dynamically between components using RxJs/BehaviorSubject


I have two sibling components and showing side-by-side, let's say Component-A & Component-B.

Component-A have form controls, once user fill out the form, I need to perform some business logic and display the data into Component-B.

I have created Service to share the data. Currently data is available Component-B when user make any changes but it's not displayed automatically, I have place "refresh" button on Component-B and when I click on the button data is getting displayed.

What I want to achieve is smooth data flow from Component-A to Component-B without any user click. For some reason I am not able to subscribe the service in Component-B.

Using @angular version ~4.0.0

Nav.Service.ts

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

@Injectable()
export class NavService {

  // Observable navItem source
  private _navItemSource = new BehaviorSubject<string>(null);

  // Observable navItem stream
  navItem$ = this._navItemSource.asObservable();

  changeNav(query: string) {
    this._navItemSource.next(query);
    console.log("Inside changeNav",query )
  }

}

Component-A

Private getSelectedComponents() {
         this._navService.changeNav(this.searchValue) //dataFromControls is string data..
         this.dataFromSisterComponent = '';   
}

HTML:

 <div class="form-group">
        <div class="form-inline">
            <label for="searchbox" class="control-label">Search : </label>
            <input id="searchbox"class="form-control" type="text" #searchValue (keyup)="0"/>
            <button class="btn btn-success" (click)="getSelectedComponents()">Add</button>
        </div>        
    </div>

Component-B

import { Component, Input, Output, EventEmitter, ViewChild, OnInit, OnDestroy} from '@angular/core';
import { FormControl, FormGroup} from '@angular/forms';
import { DataService} from '../../Services/DataService/data.service';
import { Subscription }   from 'rxjs/Subscription';
import { NavService } from '../../Services/NavService/nav.service';

@Component({
    moduleId: module.id,
    selector:'ComponentB',
    templateUrl: 'Component-B.component.html',
})
export class Component-B implements OnInit {
    subscription: Subscription;
    dataFromComponentA: string;

   shows: any;
   error: string;
   item: string;

    constructor(private dataService: DataService,private _navService: NavService)
    {    
    }

    ngOnInit() {
       this.getQuery(); 
    }

    getQuery() {
        this.subscription = this._navService.navItem$
         .subscribe(
         item => this.item = item,
          err => this.error = err
         );
        dataFromComponentA=this.item 
        console.log("Inside getquery",this.item )
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        console.log("ngOnDestroy")
    }
}

HTML

In below html, I want to display data automatically in {{dataFromComponentA}} when user made changes in ComponentA. Currently data is getting displayed when I click on "Refresh" button and I wanted to avoid this button click.

<h3>Template Components 123 </h3>
<button class="btn btn-success" (click)="getQuery()">Refresh</button>
<p><b>Value coming from Component-A</b>
  {{ dataFromComponentA }}
  OK </p>

Solution

  • You need the code inside the callback you pass to subscribe

    getQuery() {
        this.subscription = this._navService.navItem$
         .subscribe(
           item => {
             this.item = item,
             dataFromComponentA=this.item 
             console.log("Inside getquery",this.item )
           },
           err => this.error = err
         );
    }