我是Angular的新手,目前正在使用Angular6进行开发。这是我的查询。在我的应用程序启动之前,我需要调用三个服务,为我提供应用程序的一些配置。让我们将服务称为Initialization,Conifg和UserDetails。所以我在app-module.ts文件中添加了如下服务。
`
export function init_app(initService: InitializationService) {
return () => initService.getInit();
}
export function get_settings(configService: ConfigService) {
return () => configService.getConfig();
}
export function get_user_settings(userDetails: UserDetailsService) {
return () => userDetails.getSettings();
}
@NgModule({
imports: [/*my-imports*/],
providers: [
AppLoadService,
{ provide: APP_INITIALIZER, useFactory: init_app, deps: [InitializationService], multi: true },
{ provide: APP_INITIALIZER, useFactory: get_settings, deps: [ConfigService], multi: true },
{ provide: APP_INITIALIZER, useFactory: get_user_settings, deps: [UserDetailsService], multi: true }
]
})
`现在,InitializationService具有其他两个服务正常工作所需的一些值。在app_init中,服务请求立即发送。
我需要在调用InitializationService时才调用ConfigService和UserDetailsService。
为了解决这个问题,我做了以下工作,
// AppConfig.ts
export class AppConfig {
public static Config= {};
public static $subject = new Subject();
}
// InitializationService
getInit () {
const promise = new Promise((resolve, reject) => {
this.http.get().then(val => {
AppConfig.config = val;
AppConfig.$subject.next(val);
});
};
return promise;
}
//的ConfigService
getConfig () {
if(AppConfig.Config.baseUrl === undefined) {
AppConfig.$subject.subscribe(val => {
this.http.get(AppConfig.Config.baseUrl).then(//doSomething);
})
}
}
所以我创建了一个静态主题并订阅它。一旦Init服务完成,它就会发送主题的下一个值,现在由Config服务订阅和监听。收到订阅电话后,我会进行进一步的操作。
我的UserDetails getSettings()调用重复相同的代码。
我的方法是否正确?是否有任何其他模式尝试和测试。
有什么建议或更好的方法来解决上述问题?
提前致谢。
问候,hawx
使用一个初始化器并控制整个流程:
export function initAll(initService: InitializationService, configService: ConfigService, userDetails: UserDetailsService) {
return () => {
return initService.getInit().pipe(
switchMap(() => {
return flatMap([ConfigService.getConfig(), userDetails.getSettings()]);
}),
);
}
}
请注意,flatMap
假设两项操作都已完成;但这只是一种方法。您可以通过rxjs运算符完全控制该过程。而且,你只有一个APP_INITIALIZER
// app-module代码
export function initAll(appInitService:AppInitService, configService:ConfigService) {
// return a promise because thats what the app_init token expects. there is an open ticket with angular related to this. https://github.com/angular/angular/issues/15088
return () => {
const promise = new Promise((resolve, reject) => {
appInitService.load().then(() => {
configService.fetch().then(() => {
resolve();
});
});
});
return promise;
}
}
//appInitService.load()调用
const promise = this.http.get<any>(`myConfigURL`).toPromise();
promise.then(response => {
Object.assign(AppConfig.ENV, response.value.parameters);
});
return promise;
//配置服务调用
const promise = this.http.get<any>(myConfigUrl).toPromise();
promise.then(response => {
//do something with response
});
return promise;
我采用这种方法是因为它解决了我拥有和维护主题的问题。另外,我没时准备尝试调试Observable的问题。
谢谢你的回应。