Reputation: 961
I have an angular 2 application that in a component call ComponentB, displays multiple time the same component, that we call ComponentA. This ComponentA had a related Service that I use to make the calls, and when these calls gets an answer the service sends an observable object that must be catch from the ComponentA. What I need is that ComponentA number 1 must catch only the stream of a Service initialized into ComponentA number 1, so that ComponentA 2 in the same change remain the same.
Try to make an example
<componentA *ngFor="let el of list"></componentA>
@Component({
selector:"componentB",
templateUrl:"./componentB"
styleUrls:["./componentB.css"]
})
export class ComponentB implements OnInit{
ngOnInit(){}
private list:string[]=['','']
}
<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 ...
}
}
What's wrong in this code? I thought that it would be the solution with the private apposition in the constructor of the component A, but it seems not work and everything change.
To be more precise, in example i need that: if I click the button in first element of component A inside component B I don't want the value of 'variable' to be changed in the second component A inside component B.
Upvotes: 2
Views: 609
Reputation: 13356
Try Setting a provider of ServiceA for each ComponentA so there will be multiple instances of ServiceA (it's not singleton) that separately serves each ComponentA. Remove the serviceA from the providers array in your module.
@Component({
selector:"componentA",
templateUrl:"./componentA",
styleUrls:["./componentA.css"],
providers: [ serviceA ]
})
export class ComponentA implements OnInit{
constructor(private sA:serviceA){
// ...
}
}
Upvotes: 1