//--- ШАГ 1: Конфигурация среды
Код: Выделить всё
@Injectable({
providedIn: "root"
})
export class EnvironmentConfiguration {
public production = false;
[key: string]: unknown;
}
Код: Выделить всё
export const environmentConfiguration: EnvironmentConfiguration = {
production: false,
// Adding extra key-value pairs to the config
enableAuthentication: true,
enableSSO: false
}
Эта функция инициализации службы вызывается во время запуска приложения для добавления дополнительной информации с сервера в объект среды
Код: Выделить всё
@Injectable({
providedIn: 'root'
})
export class EnvironmentConfigurationService {
private informationService = inject(InformationService);
private environment: EnvironmentConfiguration = new EnvironmentConfiguration();
get Environment(): EnvironmentConfiguration {
return this.environment;
}
public initializeEnvironment(angularConfig: EnvironmentConfiguration): Promise {
this.environment = angularConfig;
this.informationService.getInformation().pipe(finalize(() => resolve())).subscribe({
next: result => {
// Here am adding extra info from the server to the environment object
this.environment['shelf'] = result.shelf?.id;
this.environment['table'] = result.table?.id;
this.environment['carpet'] = result.carpet?.id;
},
error: err =>
this.logger.error('Problem loading application info', err);
complete: () => this.logger.debug('Merging info with Angular environment config')
});
}
}
Код: Выделить всё
export function provideEnvironmentConfig(environmentConfig: EnvironmentConfig): EnvironmentProviders {
return makeEnvironmentProviders([
provideAppInitializer(() => {
const environmentConfigurationService = inject(EnvironmentConfigurationService);
return environmentConfigService.initEnvironment(environmentConfig)
})
]);
}
Код: Выделить всё
@Injectable({
providedIn: 'root'
})
export class MenuService {
private environmentConfigurationService = inject(EnvironmentConfigurationService);
// In this method i want to have access to the values added to the environment object from the server. When i log the whole object i see that values from the server are present but when i try to extract a specific value using the bracket notation i get undefined, very weird behavior i don't understand.
processMenu() {
const config = this.environmentConfigurationService.EnvironmentConfig;
console.log(config) // displays the whole object including values from the server
const shelf = config['shelf'];
console.log(shelf) // displays undefined
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... ndex-signa