1

我需要为OAuthModule配置动态 URL,以便在每次请求时发送访问令牌。我正在使用的解决方案(提示)通过工厂方法提供 OAuthModuleConfig 似乎不起作用。

这是我的 AppModule,我在其中配置所有内容:

import {BrowserModule} from '@angular/platform-browser';
import {APP_INITIALIZER, NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {OAuthModule, OAuthModuleConfig} from 'angular-oauth2-oidc';
import {HttpClientModule} from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MaterialModule} from './material/material.module';
import {DataSharingService} from './data-sharing/data-sharing.service';
import {EnvironmentService} from './environment/environment.service';
import {environment} from '../environments/environment';
import {ApiModule, BASE_PATH} from '@api/api-client';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    APIModule,
    HttpClientModule,
    OAuthModule.forRoot(),
    BrowserAnimationsModule,
    MaterialModule
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: appInitializerFactory,
      deps: [EnvironmentService, DataSharingService],
      multi: true
    },
    {
      provide: OAuthModuleConfig,
      useFactory: oAuthModuleConfigFactory,
      deps: [DataSharingService]
    },
    {
      provide: BASE_PATH,
      useFactory: basePathFactory,
      deps: [DataSharingService]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

function appInitializerFactory(environmentService: EnvironmentService, dataSharingService: DataSharingService): () => Promise<void> {
  return () => environmentService.getEnvironment(environment.production)
    .toPromise()
    .then(value => {
      dataSharingService.apiBasePath.next(value.API_BASE_PATH);
    });
}

function oAuthModuleConfigFactory(dataSharingService: DataSharingService): OAuthModuleConfig {
  return {
    resourceServer: {
      allowedUrls: [dataSharingService.apiBasePath.value],
      sendAccessToken: true
    }
  };
}

function basePathFactory(dataSharingService: DataSharingService): string {
  return dataSharingService.apiBasePath.value;
}

我想我应该将此配置传递给OAuthModule.forRoot()导入中的方法,但我不知道如何。

如何将提供的内容传递OAuthModuleConfigOAuthModule.forRoot()?

4

0 回答 0