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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With