简体   繁体   中英

Angular 2 how to pass config to provider from app.module.ts

I'm trying to make angular 2 service with config file passed through constructor so i can read the config after it initializes and start other part of the code. I'm trying to make config file in app.module.ts and trough provider use factory to pass it down to my service but i have no luck, I've been stuck searching for google answers but i can't find the right solution. My code is bellow, i created config

app.module.ts

const config = new AuthServiceConfig([
  {
    id: FacebookLoginProvider.PROVIDER_ID,
    provider: new FacebookLoginProvider(),
  },
  {
    id: LinedinLoginProvider.PROVIDER_ID,
    provider: new LinedinLoginProvider(),
  },
]);

export function provideConfig() {
  return config;
}
export function configFactory(config: AuthServiceConfig) {
  return config;
}
 providers: [
     ...
    { provide: AuthServiceConfig, useFactory: provideConfig },
    { provide: AuthProvider, useFactory: config },
  ],

auth.ts

    export interface AuthServiceConfigItem {
  id: string;
  provider: Provider;
}
export class AuthServiceConfig {
  providers: Map<string, Provider> = new Map<string, Provider>();

  constructor(providers: AuthServiceConfigItem[]) {
    for (let i = 0; i < providers.length; i++) {
      let element = providers[i];
      this.providers.set(element.id, element.provider);
    }
  }
}

@Injectable()
export class AuthProvider {
  private static readonly ERR_LOGIN_PROVIDER_NOT_FOUND =
    'Login provider not found';
  providers: Map<string, Provider> = new Map<string, Provider>();

  constructor(config) {
    this.providers = config.providers;
    console.log('Ovo su providersi u konstruktoru', this.providers);
  }

I haven't tried dynamically change providers, but I used the Angular CLI environment files. Based on some flag from the environment file I would instantiate the proper service in the factory function.

Take a look at the app.module.ts and product.factory.ts here: https://github.com/Farata/angulartypescript/tree/master/code-samples/Angular6/chapter5/di-samples/src/app/factory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM