使用APP_INITIALIZER加载多个配置

时间:2019-02-07 19:41:36

标签: angular

我的应用程序需要在加载应用程序之前通过调用不同的方法来了解多配置。因此,作为APP_INITIALIZER的一部分,我在方法中具有loadUsername和loadUserRoles。下面的方法效果很好,但是我认为这不是两次调用APP_INITIALIZER的标准做法。任何人都可以在这里帮助我。

import { ConfigService } from './auth/config.service';
import { AccessControlService } from './shared/access-control.service';

export function loadUsername(configService: ConfigService) {
  return () => configService.setUserName();
}

// based on pool api
export function loadUserRoles(accessControlService: AccessControlService) {
  return () => accessControlService.accessControlData();
}


@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
   // Many Modules
  ],
  providers: [
    ConfigService,
    AccessControlService,
    {
      provide: APP_INITIALIZER,
      useFactory: loadUsername,
      deps: [ConfigService],
      multi: true
    },
    {
      provide: APP_INITIALIZER,
      useFactory: loadUserRoles,
      deps: [AccessControlService],
      multi: true
    },

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

我的config.service.ts是:

import { Injectable, isDevMode } from '@angular/core';
import { Constants } from '../shared/utils/constants';

@Injectable()
export class ConfigService {

  public userSource: BehaviorSubject<string | undefined> = new BehaviorSubject<string | undefined>(undefined);

  constructor() { }

  setUserName(): Promise<Object> {
      return of(Constants.userName) // this could be a http request
      .pipe(
        tap(userName => {
          this.userSource.next(userName);
        })
      )
      .toPromise();
  }
}

access-control.service.ts

import { Injectable, isDevMode } from '@angular/core';

import { tap } from 'rxjs/operators';
const CACHE_SIZE = 1;

@Injectable()
export class AccessControlService {

  public accessControlObj: BehaviorSubject<object | undefined> = new BehaviorSubject<object | undefined>(undefined);

  constructor() { }

    private cache$;
    accessControlData() {
      if (!this.cache$) {
        this.cache$ = this.getRoles();
        this.accessControlObj.next(this.cache$);
      }
      return this.cache$;
    }

}

0 个答案:

没有答案