【发布时间】:2018-08-13 08:30:16
【问题描述】:
在我的应用程序中,我使用一个提供程序进行身份验证,一个提供程序用于加载应用程序配置文件。不过,auth 提供程序使用来自config 提供程序的数据。所以我希望auth 提供者等待config 提供者构造函数准备好,然后再调用它的getSelectedConfig() 方法。现在我实现了以下机制
// AuthProvider
@Injectable()
export class AuthProvider {
private url:string;
private token:string;
constructor(
public http: HttpClient,
public config: ConfigProvider
) {
this.loadParams();
}
private loadParams() {
this.config.ready().subscribe(
ready => {
this.config.getSelectedConfig().subscribe(
config => {
this.url = config.endpoint;
this.token = config.token;
}
);
}
)
}
}
// ConfigProvider (in seperate file, of course)
@Injectable()
export class ConfigProvider {
private selectedConfig:Config = null;
private configStorageKey:string = "selected_config";
public readyObservable:Observable<boolean>;
constructor(
public storage: Storage,
public http: HttpClient
) {
this.checkStorageForConfig();
}
public ready(){
return this.readyObservable;
}
public checkStorageForConfig() {
this.readyObservable = Observable.create(
observer => {
this.storage.get(this.configStorageKey).then(
config => {
if(config){
this.selectedConfig = config;
}
observer.next();
}
)
}
)
}
}
所以我创建了一个可以提供给auth 的 Observable,以了解是否已经可以使用 config 提供程序。
此方法有效,但我认为这不是一个好的解决方案。然而我想不出更好的。我一般不知道如何处理这种情况。
在我看来,我想简单地调用 this.config.ready().then( ... ) 之类的东西,而不引入其他 Observable。但也许这毕竟是正确的方法。
【问题讨论】:
-
查看 APP_INITIALIZER 以在应用加载之前加载您的配置服务
标签: angular typescript asynchronous ionic-framework storage