9

I have recently moved across to Angular 2 from Angular 1 and often run into issues trying to detect changes in the property of an object (something previous done via $watch).

The typical use case is that I will have an injectable service that maintains a piece of data, for example an object containing the settings:

@Injectable()
export class SettingsService
{
    _settings = {
        'settingA' : true,
        'settingB' : false
    }

   ...

   get settings()
   {
       return this._settings;
   }
}

I will then have a component such as a settings page in an Ionic app that will get the settings from the settings service:

constructor(private settingsService : SettingsService)
{
    this.settings = settingsService.settings;
}

And directly couple the object properties to an UI component like a toggle. The problem is other than calling a function on every toggle change event how can either the service or the component know that the settings object has changed to trigger an appropriate action like saving the settings to a data store?

cubiclewar
  • 1,569
  • 3
  • 20
  • 37

1 Answers1

9

To build an observable data service you could use BehaviorSubject from rxjs. You create an subject in your service and then you have to subscribe this subject in your components.

Take a look here for some tutorials about creating services with it: example 1, example 2.

You have theoretically the opportunity to use EventEmitter in your service. But you shouldn't use it. Take a look at this answer for more details. In this answer you can find also a example how to solve it with using Observable instead of BehaviorSubject

muetzerich
  • 5,600
  • 7
  • 37
  • 52
  • It seems using a BehaviorSubject still requires a function call when the toggle changes state rather than just being able to pick up the change in the service. Good notes on using EventEmitter though, I have used them elsewhere to notify components of data updates in services. – cubiclewar Jul 09 '16 at 22:53
  • I am having the same issue..did you find any solutions for this? – Febin Mathew Nov 25 '18 at 10:37