【问题标题】:Angular 2 multiple component with a private observer带有私人观察者的 Angular 2 多组件
【发布时间】:2017-06-15 13:49:10
【问题描述】:

我有一个 Angular 2 应用程序,它在一个名为 ComponentB 的组件中多次显示同一个组件,我们称之为 ComponentA。这个 ComponentA 有一个相关的服务,我用它来进行调用,当这些调用得到响应时,服务会发送一个必须从 ComponentA 捕获的可观察对象。 我需要的是 ComponentA 编号 1 必须仅捕获初始化为 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>

打字稿

@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 中更改“变量”的值。

【问题讨论】:

  • 能否请您提供有关您的问题的任何 plunker
  • 好的,但是我的应用真的很大,我会写一个示例,但我需要一点时间。
  • 您的问题的任何小代码库副本都会很棒
  • @mautrok:请您修正您对问题的描述。我理解正确吗。我需要的正是您希望 Observable http 调用缓存而不是缓存的时间。

标签: angular typescript rxjs observable


【解决方案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){
        // ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 2016-08-26
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多