Angular Universal:在 APP_INITIALIZER 之前初始化延迟加载的模块

Dav*_*vid 5 angular-universal angular

我的应用程序用于APP_INITIALIZER在初始化应用程序之前从 json 文件动态检索一些配置。

当使用 Angular Universal 时,延迟加载的模块是在使用时返回的承诺APP_INITIALIZER解决之前在服务器端创建的。

当不使用角度通用时,这效果很好。这是角度通用的错误,还是我做错了什么?

应用程序模块.ts

export function loadConfigService(configService: AppConfigService): Function
{
  return () => {
    return configService.load();
  };
}

@NgModule({
    //...
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: loadConfigService,
      deps: [AppConfigService],
      multi: true
    },
Run Code Online (Sandbox Code Playgroud)

应用程序配置.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);
      });

    });
  }
}
Run Code Online (Sandbox Code Playgroud)

子模块

import {APP_CONFIG} from "@utils/services/app-config.service";

export class LazyChildModule
{
  constructor()
  {
   console.log('in child constructor');
   //Here, APP_CONFIG is null
Run Code Online (Sandbox Code Playgroud)

无通用输出:

in load
in response
in child constructor
Run Code Online (Sandbox Code Playgroud)

通用输出:

in load
in child constructor
in response    
Run Code Online (Sandbox Code Playgroud)