APP_INITIALIZER не запускается перед фабрикой - PullRequest
0 голосов
/ 24 октября 2018

Я использую APP_INITIALIZER для загрузки переменных среды.Мне нужно использовать эти переменные внутри моего authConfigFactory, но фабрика продолжает загружаться до завершения APP_INITIALIZER внутри конфигурации приложения.

Я использую эту библиотеку: https://github.com/manfredsteyer/angular-oauth2-oidc

Я хочу использовать значение APP_CONFIG.authConfig.allowedUrls внутри моей фабрики конфигурации аутентификации.Как я могу убедиться, что он устанавливает конфигурацию в первую очередь перед фабрикой аутентификации.

Я получаю эту ошибку на фабрике: Cannot read property 'authConfig' of undefined

app.module.ts:

providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: (config: AppConfigService) => () => config.load(),
      multi: true,
      deps: [AppConfigService]
    },
    {
      provide: OAuthModuleConfig,
      useFactory: authConfigFactory
    }
]

app.config.ts:

export let APP_CONFIG: AppConfig;

@Injectable()
export class AppConfigService {
  constructor(
    private injector: Injector
  ) {}

  config = null;

  public load() {
    const http = this.injector.get(HttpClient);

    return http
      .get('../assets/config/config.json')
      .pipe(
        tap(returnedConfig => {
          const t = new AppConfig();
          APP_CONFIG = Object.assign(t, returnedConfig);
        })
      )
      .toPromise();
  }

}

auth-config-factor:

export function authConfigFactory(): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: APP_CONFIG.authConfig.allowedUrls,
      sendAccessToken: true
    }
  };
}

Ответы [ 2 ]

0 голосов
/ 03 ноября 2018

У меня та же проблема, и я ее исправляю.

module-factory:

import { InjectionToken } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { AuthorizationService } from './authorization.service';

export const AUTH_CONFIG = new InjectionToken<string>('auth.config.path', {
    factory: () => 'config.json',
  });


  export function CheckAuthorizationState(handler: HttpBackend, authService: AuthorizationService, path: string) {
    return async () => {
      const http = new HttpClient(handler);
      // get config for authorization
      await http.get(path)
        .pipe(
          map((response: any) => {
            authService.init(response);
          })
        ).toPromise();
      // check authorization
      await authService.checkAuthorization();
    };
  }

module:

import { NgModule, APP_INITIALIZER, ModuleWithProviders, InjectionToken } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AuthorizationService } from './authorization.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthorizationGuardService } from './authorization-guard.service';
import { AuthorizationInterceptor } from './authorization-interpretator';
import { HttpBackend, HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { CheckAuthorizationState, AUTH_CONFIG } from './module-factories';




@NgModule({
  imports: [
    CommonModule
  ],
  providers: [
    AuthorizationService,
    AuthorizationGuardService,
    {
      provide: APP_INITIALIZER,
      useFactory: CheckAuthorizationState,
      deps: [HttpBackend, AuthorizationService, AUTH_CONFIG],
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthorizationInterceptor,
      multi: true
    }
  ],
  declarations: []
})

export class AuthorizationModule {
  static forRoot(path: string): ModuleWithProviders {
    return {
      ngModule: AuthorizationModule,
      providers: [
        { provide: AUTH_CONFIG, useValue: path }
      ]
    };
  }
}

Вот моя библиотека авторизации, которая публикует для вас: https://www.npmjs.com/package/sso-authorization-oidc-client

0 голосов
/ 24 октября 2018

У меня уже была эта проблема, и я попробовал много возможностей без удачи, единственное решение - я использовал ngrx / store

В app.config.ts вы можете отправить действие, чтобы сохранить конфигурацию вмагазин, и вы можете получить его после этого в других сервисах, выполнив: store.select () Подпишитесь на него и выполняйте свой контроль

app.module.ts

providers: [
 AuthService, // oidc-client.ts where i need the config from json
 DataService,
 ConfigService,
 {
  provide: APP_INITIALIZER,
  useFactory: loadConfig,
  deps: [ConfigService],
  multi: true,
 },

config.service.ts

  import { HttpClient } from '@angular/common/http';
  import { Injectable } from '@angular/core';
  import { Store } from '@ngrx/store';
  import { IAppStore } from '../models/store.model';
  import * as ConfigActions from '../store/actions/config.actions';

  @Injectable()
   export class ConfigService {
   public config: any = {};

   constructor(private http: HttpClient, private store: Store<IAppStore>) {}

   getConfig(key: string): string {
     return this.config[key] || '';
    }
  public loadConfig() {
     return new Promise((resolve, reject) => {
      this.http.get('app-config.json').subscribe(
      (response) => {
        this.config = response;
        this.store.dispatch(new ConfigActions.AddConfig(response)); // dispatch action to update the store
        resolve(true);
      }
    );
  });
  }}

AuthService

  import { Log, User, UserManager, WebStorageStateStore } from 'oidc-client';
  ...
  @Injectable()
  export class AuthService {
  private _userManager: UserManager;
  public _user: User;
  constructor(
    private store: Store<IAppStore>
    private httpClient: HttpClient,
    private route: Router,
    private configs: ConfigService
  ) {
this.store.select('appConfig').subscribe((configdata) => {
  Log.logger = console;
  const config = {
  authority: configdata.stsAuthority,
  client_id: configdata.clientId,
  redirect_uri: `${configdata.clientRoot}/#/auth-callback#`,
  scope: 'openid profile fusionApi.full_access',
  response_type: 'id_token token',
  post_logout_redirect_uri: `${configdata.clientRoot}?postLogout=true`, // delet all stored tokens after logout
  userStore: new WebStorageStateStore({ store: window.localStorage }),
  automaticSilentRenew: true,
  silent_redirect_uri: `${configdata.clientRoot}/assets/html/silent-refresh-redirect.html`,
};
  this._userManager = new UserManager(config);
  this._userManager.getUser().then((user) => {
  if (user && !user.expired) {
    this._user = user;
  }
});
 ...
}

login(): Promise<any> {
 return this._userManager.signinRedirect();
}
...
...