AngularOne
AngularOne

Reputation: 2860

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

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.

Upvotes: 2

Views: 1118

Answers (1)

Powkachu
Powkachu

Reputation: 2268

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

Upvotes: 4

Related Questions