如何从指令中观察服务内的简单变量更改? [英] How to watch from directive on a simple variable changes inside a service?

查看:19
本文介绍了如何从指令中观察服务内的简单变量更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 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));

我错过了什么?我应该声明可观察的吗?为什么和在哪里?我不确定这是否是解决此问题的正确方法,因为这不是 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屋!

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