Created
November 17, 2016 07:18
-
-
Save ranakrunal9/7b26ccafbe29fcf4bdac4f9236e71e6a to your computer and use it in GitHub Desktop.
Parent and children communicate via a service in Angular2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit, OnDestroy } from '@angular/core'; | |
import { Subscription } from 'rxjs/Subscription'; | |
import { CommonService } from './common.service'; | |
@Component({ | |
selector : 'child', | |
templateUrl : './child.html' | |
}) | |
export class ChildComponent implements OnInit, OnDestroy { | |
private subscription: Subscription; | |
constructor( private commonService: CommonService ){ | |
} | |
ngOnInit() { | |
this.subscription = this.commonService.notifyObservable$.subscribe((res) => { | |
if (res.hasOwnProperty('option') && res.option === 'call_child') { | |
console.log(res.value); | |
// perform your other action from here | |
} | |
}); | |
} | |
ngOnDestroy() { | |
this.subscription.unsubscribe(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable, Inject } from '@angular/core'; | |
import { Subject } from 'rxjs/Subject'; | |
@Injectable() | |
export class CommonService { | |
private notify = new Subject<any>(); | |
/** | |
* Observable string streams | |
*/ | |
notifyObservable$ = this.notify.asObservable(); | |
constructor(){} | |
public notifyOther(data: any) { | |
if (data) { | |
this.notify.next(data); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit, OnDestroy } from '@angular/core'; | |
import { Subscription } from 'rxjs/Subscription'; | |
import { CommonService } from './common.service'; | |
@Component({ | |
selector : 'parent', | |
templateUrl : './parent.html' | |
}) | |
export class ParentComponent implements OnInit, OnDestroy { | |
constructor( private commonService: CommonService ){ | |
} | |
ngOnInit() { | |
this.commonService.notifyOther({option: 'call_child', value: 'From child'}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment