Monday, 23 July 2018

data transfer from any component to any component USING rxjs | Angular 4

data transfer from any component to any component USING rxjs | Angular 4

Data.Service
import { Injectable } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {
private messageSource=new BehaviorSubject<string[]>(['Default Message','Message2']);
currentMessage=this.messageSource.asObservable();
constructor() { }

changeMessage(message:string[]){
this.messageSource.next(message);
}
}
Parent.component
import { Component, OnInit,ViewChild,AfterViewInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
selector: 'app-parent',
template: `<p> Parent Component!{{message}}</p>
<app-chiled></app-chiled>`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
message:string;

constructor(private data:DataService) { }

ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message[0]);
}
}
Child Component
import { Component, OnInit, Input,Output,EventEmitter } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-chiled',
template: `<p>child component :{{message}}{{message2}}</p>`,
styleUrls: ['./chiled.component.css']
})
export class ChiledComponent implements OnInit {
message: string;
message2: string;
constructor(private data:DataService) { }

ngOnInit() {
this.data.currentMessage.subscribe(msg => this.message = msg[0],msg=> this.message2=msg[1]);
}
}
Sibling Component
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
selector: 'app-sibling',
template: `<p> sibling works!{{message}}</p>
<input type="button" value="change Message" (click)=newMessage()>`,
styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

message: string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message[1]);
}
newMessage(){
this.data.changeMessage(['message Change']);
}
}

Output:

Parent Component!Default Message
child component :Default Message
sibling works!Message2


after click button

Parent Component!message Change
child component :message Change
sibling works!

No comments:

Post a Comment

IIS deployment support details

  Node JS - IIS deployment support details node: http://go.microsoft.com/?linkid=9784334 IISNode: https://github.com/azure/iisnode/releases/...