如何检测Angular2中的变量变化 [英] How to detect variable change in Angular2

查看:212
本文介绍了如何检测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?

推荐答案

好吧,如建议使用Observables一样,这确实不是那么麻烦,并且效果很好.实际上不超过几行.

Well, as suggested use Observables, this is not really such a big hassle and it works quite well. It's not more than a few lines actually.

在某些公共服务中声明它们共享的服务,例如,在该模块中声明为提供者的服务,这样就不会以同一服务的两个实例结尾.在该服务中添加Subject和一种发出值的方法:

Declare in some common service, a service that they share as same, e.g 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:

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;
  })
}

在父子互动中使用上面的代码工作的plunker:

Working plunker with above code in a parent-child interaction:

关于您对@Input()的评论,当父组件与子组件交互时,效果很好,因此在这种情况下,这对您实际上不起作用.

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.

这篇关于如何检测Angular2中的变量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆