IONIC确保之前加载了服务

时间:2017-11-19 19:01:08

标签: javascript typescript ionic-framework ionic3

我正在使用IONIC和打字稿编写应用程序。 我创建了一个存储提供程序和一个网络提供程序(请参阅下面的伪代码)。

存储提供商

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

    getSettings() {
        return this.settings;
    }
}

网络提供商

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

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

当我现在调用函数getData()时,可能会发生设置未定义,因为SettingsService仍在加载设置。如何在设备完全加载之前在NetworkProvider中等待?

目前我正在使用setTimeout检查设置是否已加载。但我对此并不满意。

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

使用承诺怎么样?

如下所示:

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
       });
    }
  }

另外我认为存储性能很好,所以也许你也可以在SettingsService中省去设置变量,只是总是从存储中获取值...但我当然不知道你的应用程序,只是一个想法

P.S。:不要忘记只能在platform.ready()

之后使用存储空间

答案 1 :(得分:0)

存储提供商

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

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

网络提供商

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

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

    }
}
相关问题