我有一个 Angular 2 应用程序,它在组件调用 ComponentB 中多次显示同一个组件,我们称之为 ComponentA。这个 ComponentA 有一个相关的服务,我用它来进行调用,当这些调用得到响应时,服务会发送一个必须从 ComponentA 捕获的可观察对象。 我需要的是 ComponentA 编号 1 必须只捕获 Service 初始化为 ComponentA 编号 1 的流,以便相同更改中的 ComponentA 2 保持不变。
试着做个例子
HTML 组件 B
<componentA *ngFor="let el of list"></componentA>
TYPESCRIPT 组件 B
@Component({
selector:"componentB",
templateUrl:"./componentB"
styleUrls:["./componentB.css"]
})
export class ComponentB implements OnInit{
ngOnInit(){}
private list:string[]=['','']
}
HTML 组件A
<div>{{variable}}</div>
<button (click)="changeVariable()"></button>
typescript
@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 的构造函数中私有(private)同位的解决方案,但它似乎不起作用,一切都变了。
更新
更准确地说,例如我需要:如果我单击组件 B 内组件 A 的第一个元素中的按钮,我不希望在组件 B 内的第二个组件 A 中更改“变量”的值。
最佳答案
尝试为每个 ComponentA 设置一个 ServiceA 提供者,这样会有多个 ServiceA 实例(它不是单例)分别为每个 ComponentA 提供服务。从模块中的提供程序数组中删除 serviceA。
@Component({
selector:"componentA",
templateUrl:"./componentA",
styleUrls:["./componentA.css"],
providers: [ serviceA ]
})
export class ComponentA implements OnInit{
constructor(private sA:serviceA){
// ...
}
}
关于具有私有(private)观察者的 Angular 2 多组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41935322/