2017-09-30 3 views
-1

これは私が "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つのインスタンスのために変更が速すぎる

答えて

1

BehaviorSubjectを使用すると、この種類の機能を実現できます。 最初のコンポーネントが変更された場合、その変更をBehaviorSubjectにプッシュし、次にsubscribeを第2コンポーネントのプッシュに変更することができます。これにより、最初のコンポーネントに表示されている変更が適用されます。 あなたは、あなたが書くことができ、あなたの最初のコンポーネントでは、

import { Injectable } from '@angular/core'; 
@Injectable() 
export class DataService 
{ 
dataSubject: BehaviorSubject; 
constructor() 
{ 
this.dataSubject = new BehaviorSubject(null); 
console.log("new instance"); 
    } 
pushChanges(dataValue) { 
    this.dataSubject.next(dataValue); 
} 
getChanges() { 
    return this.dataSubject.asObservable(); 
} 
dataValue: string = "initial value"; 
} 

をこのような何かを行うことができます。このプロセスを繰り返すことができ

this._dataService.getChanges().subscribe( 
changeByFirstComponent => { 

    // this method will be triggered only when there is change in first component 
    // and it's pushed on the `dataSubject` 

    console.log(changeByFirstComponent); 
} 
) 

this._dataService.pushChanges(this.ChangeByFirstComponent); 

そして、あなたの第二の成分で 、あなたは逆の機能も望んでいます。

+0

天才ありがとうございました – Faraz

+0

嬉しいです:) –

関連する問題