简体   繁体   English

如何检测Angular2中的变量

[英]How to detect variable change in Angular2

I have the following config object which is set before the constructor is running: 我有以下配置对象,它在构造函数运行之前设置:

config: Object = {
     onSlideChangeEnd : function(slide:any) {
          this.currentSlideIndex = slide.activeIndex;
     }
};

I want to notify a service about the change, the problem is that the service is not available yet when the configuration is set: 我想通知服务有关更改,问题是在设置配置时服务还不可用:

 constructor(private user: UserService,
             private layout: LayoutService) {
 }

How can I notify the service on this variable change? 如何通过此变量更改通知服务?

Well, as suggested use Observables, this is not really such a big hassle and it works quite well. 好吧,正如建议使用Observables,这不是一个非常大的麻烦,它运作得很好。 It's not more than a few lines actually. 实际上它不过几行。

Declare in some common service, a service that they share as same, eg a service declared as provider in that module, so that you do not end up with two instances of the same service. 在一些公共服务中声明它们共享的服务,例如在该模块中声明为提供者的服务,这样您就不会得到同一服务的两个实例。 Add a Subject to that service and a method to emit value: 向该服务添加Subject和发出值的方法:

public configObservable = new Subject<number>();

emitConfig(val) {
  this.configObservable.next(val);
}

And in the component you need to set the config: 在组件中,您需要设置配置:

emit(val) { // your value you want to emit
  this.myService.emitConfig(val);
}

And then subscribe to the value where you need it: 然后订阅您需要的值:

constructor(private myService: MyService) {
  this.myService.configObservable.subscribe(value => {
    this.value = value;
  })
}

Working plunker with above code in a parent-child interaction: 在父子互动中使用以上代码工作的plunker:

Plunker Plunker

As to your comment about @Input() , that works well when a parent component-child interaction, so that wouldn't really work for you in this case. 至于你对@Input()评论,这在父组件 - 子交互时很有效,所以在这种情况下这对你不起作用。

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

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