[英]How to detect variable change in Angular2
我有以下配置对象,它在构造函数运行之前设置:
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()
评论,这在父组件 - 子交互时很有效,所以在这种情况下这对你不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.