How to Broadcast Data From Service To Controller In Angular 4

Posted By : Ranjan Mondal | 23-Dec-2017

Introduction: 


Observable is like an array whose data arrive asynchronously over the time. It helps you manage asynchronous data, such as data coming from a backend and also used within Angular itself, including Angular’s event system and its http client service.
Angular uses a third-party library called Reactive Extensions (RxJS) to use Observables. It is a proposed feature for ES 2016, the next version of JavaScript.

 

Following are steps To BroadCast Data.

Step 1:  Inject Subject and Observales in your Service.ts from where you want to broadcast to controller. Eg we have BroadCastService.ts

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

@Injectable()

export class BroadCastService {
    token: string;
    subject = new Subject<any>();

    constructor(private router: Router) { }

    sendMessage(data) {
        this.subject.next(data);
    }

    clearMessage() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
	
    generateObject() {
	for(let index=0;index < 5; index++){
		this.sendMessage({name:'ranjan', age:25});
	}
    }
}   

 

Step 2: For receiving Broadcast data into controller, you have to inject BroadCast Service here and use it getMessage Function. It will receive data now. You can have multiple controller who can listen to same BroadCast Data. Eg we have ReceiverComponent.ts

import { Router,ActivatedRoute,Params} from '@angular/router';
import {ToasterService} from 'angular2-toaster';
import { BroadCastService } from '../services/broadCast.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector:'receiver',
  template: require('./receiver.component.html'),
  providers: []
})

export class ReceiverComponent implements OnInit{
    constructor( private router : Router, private toasterService: ToasterService, private broadCastService: BroadCastService) {
         this.subscription = this.broadCastService.getMessage().subscribe(data => {
	        console.log('BroadCast data : ' + JSON.stringify(data));
	 	this.userList.push(data);
         });
    }

    spinner:any;
    userList = [];
    subscription: Subscription;
}
        

Thanks.
I hope this will be helpful.

About Author

Author Image
Ranjan Mondal

Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..