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
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
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
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Ranjan Mondal
Ranjan is a bright Web App Developer, and has good knowledge of Core java, Spring and hibernate.