This is my service class in which i have one variable called " dataValue".
import { Injectable } from '@angular/core';
@Injectable()
export class DataService
{
constructor()
{
console.log("new instance");
}
dataValue: string = "initial value";
}
Here it is my first component in which i am getting and intializing the service variable with the variable i define in this component.and implementing two way data binding on component variable.
import { Component } from '@angular/core';
import { DataService } from './dataservice';
@Component({
selector: 'first',
template: `
<div>
Your Input : <input type = "text" [(ngModel)] = "ChangeByFirstComponent">
You Entered : {{ChangeByFirstComponent}}
</div>
`
})
export class FirstComponent {
constructor(private _dataService: DataService) { }
ChangeByFirstComponent: string;
get DataValue(): string {
return this._dataService.dataValue;
}
set DataValue(ChangeByFirstComponent){
{
this._dataService.dataValue = this.ChangeByFirstComponent;
}
}
and here it is my second component , doing the same thing here just as firstcomonent
import { Component } from '@angular/core';
import { DataService } from './dataservice';
@Component({
selector: 'second',
template: `
<div>
Your Input : <input type = "text" [(ngModel)] = "ChangeBySecondComponent">
You Entered : {{ChangeBySecondComponent}}
</div> `
})
export class SecondComponent {
constructor(private _dataService: DataService) { }
ChangeBySecondComponent: string;
get DataValue(): string {
return this._dataService.dataValue;
}
set DataValue(ChangeByFirstComponent) {
this._dataService.dataValue = this.ChangeBySecondComponent;
}
}
i want the functionality like if the user input something from first component, the second component will get the change too rapidly due to single instance of the service class
You can achieve this type of functionality by using
BehaviorSubject
. When there is a change in first component you can push that change toBehaviorSubject
and thensubscribe
to that in second component, so it gets the changes as they appear in first component. You can do something like this,In your first component, you can write,
And in your second component,
You can repeat this process, you want the reverse functionality too.