Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observing a change in an object property in Angular 2

Tags:

angular

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?

like image 279
cubiclewar Avatar asked Jul 09 '16 09:07

cubiclewar


1 Answers

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

like image 64
muetzerich Avatar answered Sep 19 '22 18:09

muetzerich