ค้นหาเว็บไซต์

angular - APP_INITIALIZER ไม่ทำงานก่อน factory


ฉันกำลังใช้ APP_INITIALIZER เพื่อโหลดตัวแปรเฉพาะสภาพแวดล้อม ฉันจำเป็นต้องใช้ตัวแปรเหล่านี้ภายใน authConfigFactory ของฉัน แต่ factory จะโหลดก่อนที่ APP_INITIALIZER จะเสร็จสิ้นภายในการตั้งค่าแอป

ฉันกำลังใช้ห้องสมุดนี้: https://github.com/manfredsteyer/angular-oauth2-oidc

ฉันต้องการใช้ค่าของ APP_CONFIG.authConfig.allowedUrls ภายในโรงงานการกำหนดค่า auth ของฉัน ฉันจะมั่นใจได้อย่างไรว่ามันกำหนดค่าก่อนโรงงาน auth

ฉันได้รับข้อผิดพลาดนี้ในโรงงาน: ไม่สามารถอ่านคุณสมบัติ 'authConfig' ของ 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();
  }

}

การกำหนดค่าการพิสูจน์ตัวตนตามปัจจัย:

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

คำตอบ #1

ฉันเคยมีปัญหานี้มาก่อนและลองหลายวิธีแต่ไม่ได้ผล วิธีแก้เดียวที่ใช้ได้คือฉันใช้ ngrx/store

ในไฟล์ app.config.ts คุณสามารถส่งคำสั่ง (dispatch) เพื่อบันทึกการตั้งค่าในสโตร์ และคุณสามารถดึงมันมาใช้ในบริการอื่นๆ หลังจากนั้นโดยการทำ: store.select() สมัครรับ (Subscribe) และทำการควบคุมของคุณ

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);
      }
    );
  });
  }}

บริการการยืนยันตัวตน

  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();
}
...

คำตอบ #2

ฉันมีปัญหาเดียวกันและแก้ไขมันได้

โมดูล-แฟกทอรี่:

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();
    };
  }

โมดูล :

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

บทความที่เกี่ยวข้อง