これは私が "dataValue"という1つの変数を持つ私のサービスクラスです。角2のサービスクラスの単一インスタンスを使用して2つのコンポーネントのデータを更新する方法
import { Injectable } from '@angular/core';
@Injectable()
export class DataService
{
constructor()
{
console.log("new instance");
}
dataValue: string = "initial value";
}
ここでは私がコンポーネント変数にバインド双方向のデータを実装し、このcomponent.andで定義変数とサービス変数を取得し、intializingていた中で、私の最初のコンポーネントです。
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;
}
}
、ここでそれだけで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;
}
}
として、ここで同じことをやって、私の第二の成分である私は、最初のコンポーネントからのユーザ入力に何かあれば同様の機能が欲しい、第二の成分が得られますサービスクラスの1つのインスタンスのために変更が速すぎる
天才ありがとうございました – Faraz
嬉しいです:) –