How to register a subscriber in ionic 2 correctly?

I have this ionic 2 provider:

@Injectable()
export class SettingsProvider {

    settingsData: SettingsDataModel = new SettingsDataModel(2, 2);
    subscriber = null;

    constructor(public http: Http, public storage: Storage) {
        console.log('Hello SettingsProvider Provider');
    }

    load(): void {
        this.storage.ready().then(() => {

            // Or to get a key/value pair
            this.storage.get('settingsData').then((val) => {
                this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
            });

        })
    }

    save() {
        this.storage.set('settingsData', this.settingsData);
        this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
    }

    subscribe(callback) { // how to register a subscriber the right way in ionic 2?
        this.subscriber = callback;
    }


}

      

I have implemented the possibility that another class wants to subscribe and be notified by special code (brittle), what would be the implementation that the other class could subscribe to in the correct way?

+3


source to share


1 answer


To notify another piece of code, such as another service, you can expose a visible property that represents the current series of events. We can do this using Subject

.

This is how it would look like

import { Subject } from 'rxjs/subject';

// singleton can use true privacy.
const settingsEventSource = new Subject<SettingsDataModel>();

@Injectable() export default class SettingsProvider {

  constructor(readonly http: Http, readonly storage: Storage) { }

  get settings$() {
    return settingsEventSource.asObservable(); // prevent others from sourcing events
  }

  settingsData = new SettingsDataModel(2, 2);

  async load() {
    await this.storage.ready();
    try {
      this.settingsData = await this.storage.get('settingsData');
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error loading settings.');
    }
  }

  async save() {
    try {
      await this.storage.set('settingsData', this.settingsData);
      settingsEventSource.next(this.settingsData);
    }
    catch (e) {
      settingsEventSource.error('Error saving settings.');
    }
  }
}

      



The subscriber will look like this:

import SettingsProvider from './settings-provider';
import SetttingsDataModel from './settings-data-model';

@Injectable() export default class SomeService {
  constructor(settingsProvider: SettingsProvider) {
    settingsProvider.subscribe(settings => { 
      this.settings = setttings;
    });
  }
}

      

+1


source







All Articles