Exchange data between components using service

Posted on Sept. 22, 2018
observable
component interaction
service
behavior subject
angular
1187

Expected Behaviour: using Service to exchange data between components.

Observables open up a continuous channel of communication in which multiple values of data can be emitted over time.
BehaviourSubject holds the data that needs to shared with other components. I want to define filterType behaviour subject as boolean and set default value null to filterType. Components subscribe to filterObservable which will simply return BehaviourSubject value.
Declare  function to set value to BehaviourSubject.

service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs'
@Injectable({
providedIn: 'root'
})
export class multiSelectService {
constructor() { }
private filterType=new BehaviorSubject<boolean>(null);
filterObservable= this.filterType.asObservable(); 

setfilterType(type:boolean){
this.filterType.next(type);
}}

 

To get values from observable, first initialise service variable.

private serviceVar:multiSelectService;

 

Then, subscribe to filterObservable to get value in filtertype.

this.multiSelectDialogService.filterObservable.subscribe(data=>{
this.filterType=data;
this.dialogFilterType=data;
this.diplayData()
});

 

To set value to filterType

this.serviceVar.setfilterType(true);

 




0 comments

Please log in to leave a comment.