2017-01-30 3 views
2

コンポーネントコールのComponentBにComponentAという同じコンポーネントを複数回表示する角度2のアプリケーションがあります。このComponentAには、コールに使用する関連サービスがあり、これらの呼び出しが応答を受け取ると、サービスはComponentAからキャッチしなければならない監視対象オブジェクトを送信します。 私が必要とするのは、ComponentAの番号1は、ComponentAの番号1に初期化されたServiceのストリームだけをキャッチしなければならないため、同じ変更のComponentA 2は同じままであるということです。例角2の複数のコンポーネントと専用のオブザーバ

HTML ComponentB

<componentA *ngFor="let el of list"></componentA> 

活字体ComponentB

@Component({ 
    selector:"componentB", 
    templateUrl:"./componentB" 
    styleUrls:["./componentB.css"] 
}) 
export class ComponentB implements OnInit{ 

    ngOnInit(){} 

    private list:string[]=['',''] 
} 

HTML ComponentA

<div>{{variable}}</div> 
<button (click)="changeVariable()"></button> 

活字体

を作るために

てみてください

@Component({ 
    selector:"componentA", 
    templateUrl:"./componentA" 
    styleUrls:["./componentA.css"] 
}) 
export class ComponentA implements OnInit{ 
    constructor(private sA:serviceA){ 
     sA.callObservable.subscribe(
      arg0=>this.variable=arg0 
     ) 
    } 
    private variable:any; 
    changeVariable(){ 
     this.sA.call() 
    } 
} 

サービス

@Injectable() 
export class ServiceA { 
    private item=new Subject<string>(); 

    callObservable=this.item.asObservable() 

    call(){ 
     this.getForCall().subscribe(
      arg0=>item.next(arg0) 
     ) 
    } 

    getForCall():Observable<string>{ 
     .... the call and the conversion to json ... 
    } 
} 

このコードで何が悪いですか?私はそれがコンポーネントAのコンストラクタ内のプライベートな並置を持つ解決策であると思っていましたが、うまくいかず、すべてが変化します。具体的には

UPDATE

、例の私はその必要があります:私はコンポーネントBI内部の成分Aの最初の要素のボタンをクリックする場合は、「変数」の値が第2に変更することはしたくありません

+0

は、[OK]を、あなたの問題 –

+0

で任意のplunkerを提供してくださいすることができますが、私のアプリは本当に大きいですが、私はサンプルを書きますが、私は少し時間が必要です。 – mautrok

+0

あなたの問題の任意の小さなコードベースのレプリカは素晴らしいでしょう –

答えて

1

試してみてください。それぞれのComponentAに個別にサービスするServiceA(それはシングルトンではない)のインスタンスが複数存在するように、各ComponentAに対してServiceAのプロバイダを設定してみてください。あなたのモジュール内のproviders配列からserviceAを削除します。

@Component({ 
    selector:"componentA", 
    templateUrl:"./componentA", 
    styleUrls:["./componentA.css"], 
    providers: [ serviceA ] 
}) 
export class ComponentA implements OnInit{ 
    constructor(private sA:serviceA){ 
     // ... 
    } 
} 
+0

私はそれを試して、私は仕事ではないが、私はそれが解決策になると思う.... – mautrok

関連する問題