繁体   English   中英

带有私人观察者的 Angular 2 多组件

[英]Angular 2 multiple component with a private observer

我有一个 angular 2 应用程序,它在组件调用 ComponentB 中多次显示相同的组件,我们称之为 ComponentA。 这个 ComponentA 有一个相关的服务,我用它来进行调用,当这些调用得到答复时,该服务发送一个必须从 ComponentA 捕获的可观察对象。 我需要的是 ComponentA number 1 必须只捕获初始化为 ComponentA number 1 的 Service 流,以便相同更改中的 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>

打字稿

@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 的构造函数中私有同位的解决方案,但它似乎不起作用,一切都改变了。

更新

更准确地说,在示例中,我需要:如果我单击组件 BI 内组件 A 的第一个元素中的按钮,则不希望在组件 B 内的第二个组件 A 中更改“变量”的值。

尝试为每个 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){
        // ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM