如何从指令中观察服务内部简单变量的变化? [英] How to watch from directive on a simple variable changes inside a service?
问题描述
我有一个带有data
变量的简单服务:
I have a simple service with data
variable:
import { Injectable } from '@angular/core';
@Injectable()
export class MyService {
private _data:number;
get data(): number {
return this._data;
}
set data(value: number) {
this._data = value;
}
}
现在我想从指令中捕捉到有人正在设置我的变量的情况:
Now from a directive I would like to catch whenever someone is doing set to my variable:
this.myService.data = 12345;
我试图通过订阅来做到这一点,但是在语法上缺少一些东西:
I was trying to do that with subscribe but missing something on syntax:
this.myService.data.subscribe(res => console.log(res));
我想念什么?我应该宣布obserabvle吗?为什么和在哪里? 我不确定这是否是正确的解决方案,因为这不是HTTP请求,因此更改很简单.
What am I missing? Should I declare obserabvle? Why and Where? I'm not sure is that the right approce to this problem, since this is not an HTTP request, the change is simple.
推荐答案
您可以这样实现:
在您的服务中,放置一个EventEmitter:
In your service, put an EventEmitter:
dataUpdated : EventEmitter<number> = new EventEmitter();
然后在设置数据时,在setData的末尾添加:
Then when you set your data, add at the end of setData:
this.dataUpdated.emit(this.data);
它允许通知订阅的组件该变量已更改并发送新值(您可以发送所需的任何内容).
It permits to notify to the components subscribed that the variable changed and send the new value (you can send whatever you want).
最后,在您的组件中,您会像这样被告知:
And finally in you component you can be informed like this:
constructor
(
private service: Service
)
ngOnInit()
{
this.service.dataUpdated.subscribe
(
(data: number) =>
{
//setData used, you can use new data if needed
}
);
}
这篇关于如何从指令中观察服务内部简单变量的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!