angular2 主题不订阅更改
angular2 subject not subscribing the change
我有两个组件和一个由这两个组件共享的共享服务。
shared.service.ts
// ..... top level codes are skipped
private pickAnalysisForBubble = new Subject<any>();
analysisForBubble$ = this.pickAnalysisForBubble.asObservable();
mapToggleToPointOrBubble(value) {
this.pickAnalysisForBubble.next(value);
}
utility.component.ts
在视图(utility.component.html)中,有两个单选按钮,一个是预选的:
<input type="radio" name="rdbBubblePoint" class="rdbBubblePoint" value="Point" (change)="changeToPoint($event)"> Point<br>
<input type="radio" name="rdbBubblePoint" class="rdbBubblePoint" value="Bubble" (change)="changeToPoint($event)" checked="checked"> Bubble<br>
在组件(utility.component.ts)中,有一种方法可以获取点击事件:(我已经导入了shared.service
并将其添加为提供者。)
changeToPoint(event){
# analysisInteraction is the shared service constructor
this.analysisInteraction.mapToggleToPointOrBubble(event.target.value);
}
map.component.ts
我导入了 shared.service
并添加了一个构造函数。然后在 ngOnInit
中尝试 subscribe
更改, 但这是行不通的。
# analysisInteraction is the shared service constructor
this.analysisInteraction.analysisForBubble$.subscribe(
data => {
this.DrawType = data;
console.log("Drawtype fixed");
});
我正在使用 subject
检测基于此 tutorial 的变化。我做错了什么?
我猜你们没有共享同一个服务实例。你是在启动你的应用程序时指定相应的提供程序还是在主要组件中指定:
bootstrap(AppComponent, [ SharedService ]);
或
@Component({
(...)
providers: [ SharedService ]
})
export class AppComponent {
(...)
}
如果您在子组件的 providers
属性中指定它,则您不确定共享同一个实例...
编辑
由于分层注入器,每个组件都有自己的实例,而不是共享同一个实例。因此,共享服务应作为提供者添加到 main
组件中。此外,共享服务不应包含在子组件的提供者中。
我有两个组件和一个由这两个组件共享的共享服务。
shared.service.ts
// ..... top level codes are skipped
private pickAnalysisForBubble = new Subject<any>();
analysisForBubble$ = this.pickAnalysisForBubble.asObservable();
mapToggleToPointOrBubble(value) {
this.pickAnalysisForBubble.next(value);
}
utility.component.ts
在视图(utility.component.html)中,有两个单选按钮,一个是预选的:
<input type="radio" name="rdbBubblePoint" class="rdbBubblePoint" value="Point" (change)="changeToPoint($event)"> Point<br>
<input type="radio" name="rdbBubblePoint" class="rdbBubblePoint" value="Bubble" (change)="changeToPoint($event)" checked="checked"> Bubble<br>
在组件(utility.component.ts)中,有一种方法可以获取点击事件:(我已经导入了shared.service
并将其添加为提供者。)
changeToPoint(event){
# analysisInteraction is the shared service constructor
this.analysisInteraction.mapToggleToPointOrBubble(event.target.value);
}
map.component.ts
我导入了 shared.service
并添加了一个构造函数。然后在 ngOnInit
中尝试 subscribe
更改, 但这是行不通的。
# analysisInteraction is the shared service constructor
this.analysisInteraction.analysisForBubble$.subscribe(
data => {
this.DrawType = data;
console.log("Drawtype fixed");
});
我正在使用 subject
检测基于此 tutorial 的变化。我做错了什么?
我猜你们没有共享同一个服务实例。你是在启动你的应用程序时指定相应的提供程序还是在主要组件中指定:
bootstrap(AppComponent, [ SharedService ]);
或
@Component({
(...)
providers: [ SharedService ]
})
export class AppComponent {
(...)
}
如果您在子组件的 providers
属性中指定它,则您不确定共享同一个实例...
编辑
由于分层注入器,每个组件都有自己的实例,而不是共享同一个实例。因此,共享服务应作为提供者添加到 main
组件中。此外,共享服务不应包含在子组件的提供者中。