我的应用在初始化应用之前使用APP_INITIALIZER
从json文件中动态检索某些配置。
在使用angular Universal时,在解析使用APP_INITIALIZER
时返回的承诺之前,会在服务器端创建延迟加载的模块。
当不使用角度通用镜头时,此方法效果很好。这是通用角度的错误,还是我做错了什么?
app.module.ts
export function loadConfigService(configService: AppConfigService): Function
{
return () => {
return configService.load();
};
}
@NgModule({
//...
providers: [
{
provide: APP_INITIALIZER,
useFactory: loadConfigService,
deps: [AppConfigService],
multi: true
},
app-config.service.ts
export class AppConfig
{
readonly apiUrl: string;
//other properties
}
export let APP_CONFIG: AppConfig;
@Injectable()
export class AppConfigService
{
constructor(private http: HttpClient, @Inject(PLATFORM_ID) private platformId: Object, @Optional() @Inject('serverUrl') protected serverUrl: string)
{
}
public load()
{
console.log('in load');
return new Promise((resolve, reject) => {
const isBrowser = isPlatformBrowser(this.platformId);
let baseUrl = isBrowser ? '' : this.serverUrl;
this.http.get(`${baseUrl}/assets/config/conf.json`).pipe(catchError((error: any): any => {
reject(error);
return observableThrowError('Server error');
})).subscribe((envResponse: any) => {
let t = new AppConfig();
APP_CONFIG = Object.assign(t, envResponse);
console.log('in response');
resolve(true);
});
});
}
}
子模块
import {APP_CONFIG} from "@utils/services/app-config.service";
export class LazyChildModule
{
constructor()
{
console.log('in child constructor');
//Here, APP_CONFIG is null
无通用输出:
in load
in response
in child constructor
具有通用输出:
in load
in child constructor
in response