Skip to content

ConfigService

Moe Myat Zaw edited this page Jun 15, 2020 · 7 revisions

The core service for loading and getting configuration value from configuration providers.

ConfigService Class Overview

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  /**
   * Use this property to subscribe the configuration value changes event.
   * The `valueChanges` event will only be triggered when the reload() is called and
   * the configuration value is changed.
   */
  readonly valueChanges: Observable<ConfigSection>;

  /**
   * Call this method to ensure configurations are fetched and activated.
   * Configuring `ConfigModule.configure()` with default options, this method will be called
   * automatically during the app atart.
   */
  ensureInitialized(): Observable<boolean>;

  /**
   * Call this method to reload fresh configuration values from config providers.
   */
  reload(): Observable<void>;

  /**
   * Use this method to get loaded configuration value with a given string key.
   * @param key The config key string.
   */
  getValue(key: string): ConfigValue;

  /**
   * Use this method to map loaded configuration values to the options object.
   * @param key The config key string.
   * @param optionsObj The options object to be mapped with configuration values.
   */
  mapObject<T>(key: string, optionsObj: T): T;

  /**
   * Use this method to map loaded configuration values to the instance of options class.
   * @param key The config key string.
   * @param optionsClass The options class type to be mapped.
   */
  mapType<T>(key: string, optionsClass: new () => T): T;
}

Example

import { Component } from '@angular/core';

import { ConfigService } from '@dagonmetric/ng-config';

export class IdentityOptions {
  popupRedirectUri = '';
  automaticSilentRenew = true;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  constructor(private readonly configService: ConfigService) {
    // Get registered providers
    for(const provider of this.configService.providers) {
      console.log('provider name: ', provider.name);
    }

    // Get with string key
    const configValue = this.configService.getValue('key1'));
    console.log('config value: ', configValue);

    // Get with options class type
    const identityOptions = this.configService.mapType('identity', IdentityOptions);
    console.log('identity options: ', identityOptions);

    // Value change detection
    this.configService.valueChanges.subscribe(() => {
      const lastestOptions = this.configService.mapType('identity', IdentityOptions);
      console.log('lastest options: ', lastestOptions);
    });

    // Reload the config
    this.configService.reload().subscribe(() => {
      console.log('Reloaded');
    });
  }
}

See ConfigService source file to learn more about implementation.