Passing data
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from './../data.service';
@Component({
selector: 'my-child-one',
templateUrl: './child-one.component.html'
})
export class ChildOneComponent implements OnInit {
name = 'Angular 4';
constructor(private ds: DataService) {}
ngOnInit(){
// send message to subscribers via observable subject
this.ds.sendData('Message from Child One Component!');
}
sendData(){
this.ds.sendData('Message from button Click on Child One');
}
ngOnDestroy(){
// clear message
this.ds.clearData();
}
clearData(){
// clear message
this.ds.clearData();
}
}
Get data from Sevice
import { Component } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { DataService } from './data.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
dataPassed: any;
subscription: Subscription;
constructor(private ds: DataService) {
// subscribe to home component messages
this.subscription = this.ds.getData().subscribe(x => { this.dataPassed = x;
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
Service for data
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class DataService {
private subject = new Subject<any>();
sendData(message: string) {
this.subject.next(message);
}
clearData() {
this.subject.next();
}
getData(): Observable<any> {
return this.subject.asObservable();
}
}