我有以下配置对象,它是在构造函数运行之前设置的:
config: Object = {
onSlideChangeEnd : function(slide:any) {
this.currentSlideIndex = slide.activeIndex;
}
};
我想通知服务有关更改,问题是设置配置后该服务尚不可用:
constructor(private user: UserService,
private layout: LayoutService) {
}
我如何通知服务此变量更改?
嗯,正如建议使用 Observables 一样,这并不是一个很大的麻烦,而且效果很好。实际上不超过几行。
在一些公共服务中声明它们共享相同的服务,例如在该模块中声明为提供者的服务,这样您就不会得到同一服务的两个实例。添加一个Subject
该服务和发出值的方法:
public configObservable = new Subject<number>();
emitConfig(val) {
this.configObservable.next(val);
}
在组件中您需要设置配置:
emit(val) { // your value you want to emit
this.myService.emitConfig(val);
}
然后在需要的地方订阅该值:
constructor(private myService: MyService) {
this.myService.configObservable.subscribe(value => {
this.value = value;
})
}
在父子交互中使用上面的代码进行工作:
Plunker
至于你的评论@Input()
,这在父组件与子组件交互时效果很好,因此在这种情况下这对您来说并不适用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)