2017-01-30 21 views
2

我有一個角度2應用程序,它在組件調用ComponentB中顯示多個時間相同的組件,我們稱之爲ComponentA。這個ComponentA有一個相關的服務,我用來進行調用,當這些調用得到答案時,服務發送一個必須從ComponentA中捕獲的可觀察對象。 我需要的是,ComponentA編號1必須只捕獲已初始化爲ComponentA編號1的Service的流,以便相同更改中的ComponentA 2保持不變。Angular 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() 
    } 
} 

服務A

@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的構造函數中的私有apposition的解決方案,但它似乎不起作用,並且所有內容都會更改。

UPDATE

爲了更精確,例如,在我需要的是:如果我在組分BI內的組分A的第一元件點擊按鈕不想「變量」的值在第二改變組件A內部組件B.

+0

可以請你提供任何plunker與您的問題 –

+0

好了,但我的應用程序是非常大的,我會寫一個樣品,但我需要的一點點時間。 – mautrok

+0

你的問題的任何小代碼基地副本將是偉大的 –

回答

1

嘗試爲每個ComponentA設置ServiceA的提供者,以便將有多個ServiceA(它不是單例)分別服務於每個ComponentA的實例。從模塊中的providers數組中刪除serviceA。

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

我必須嘗試一下,我不在工作,但我認爲這可能是解決方案.... – mautrok