简体   繁体   中英

IONIC make sure that service is loaded before

I'm programming an app with IONIC and typescript. I created a storage provider and a network provider (see pseudocode below).

Storage provider

class SettingsService {
    settings;
    constructor(private storage: Storage) {
        storage.get("settings").then((data) => this.settings = data);
    }

    getSettings() {
        return this.settings;
    }
}

Network provider

class NetworkService {
    constructor(private http: http, private settingsService: SettingsService) {}

    getData() {
        settings = this.settingsService.getSettings();
        //Do more stuff
    }
}

When I now call the function getData() it can happen that settings is undefined because the SettingsService is still loading the settings. How can I wait in the NetworkProvider until the settings are fully loaded?

At the moment I'm using setTimeout to check if the settings are already loaded. But I'm not happy with this.

Thanks for your help :)

What about using promises?

Something like following:

class SettingsService {
    settings = null;

    constructor(private storage: Storage) {

    }

    getSettings(): Promise<{}> {

        return new Promise((resolve) => {
            if (settings !== null) {
              resolve(settings);
            } else {
              this.storage.get("settings").then((data) => {
                  this.settings = data
                  resolve(this.settings);
               });
            }
        });
    }
}

class NetworkService {
    constructor(private http: http, private settingsService: SettingsService) {}

    getData() {
       this.settingsService.getSettings().then((settings) => {
         //Do more stuff
       });
    }
  }

Also I think that storage performances are good, so maybe you could also spare the settings variable in SettingsService and just always get the value from storage...but I don't know your app of course, just an idea

PS: Don't forget that storage should only be used after the platform.ready()

Storage provider

class SettingsService {
    settings;
    constructor(private storage: Storage) {}

    getSettings() {
        return storage.get("settings");          
}

Network provider

class NetworkService {
    constructor(private http: http, private settingsService: SettingsService) {}

    getData() {
      let settings;
       this.settingsService.getSettings().subscribe(_settings => settings=_settings;

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM