How to watch from directive on a simple variable changes inside a service?

∥☆過路亽.° 提交于 2019-12-11 01:49:45

问题


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

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.


回答1:


You can achieve this like this:

In your service, put an EventEmitter:

dataUpdated : EventEmitter<number> = new EventEmitter();

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


来源:https://stackoverflow.com/questions/43610490/how-to-watch-from-directive-on-a-simple-variable-changes-inside-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!