Inject a service to fill values in environment.ts file


Inject a service to fill values in environment.ts file



I have an angular service (clientAppSettings.service.ts). It gets the config values from backend which is a json File (appsettings.json)


angular


clientAppSettings.service.ts


appsettings.json



I require to inject the angular service, to fill in the values in environment.ts file. So, the instrumentaionKey should be retrieved from service (clientAppSettings.service.ts). Any guide is appreciated.


environment.ts


instrumentaionKey



Here is the environmen.ts file:


environmen.ts


export const environment = {
production: false,
appInsights: {
instrumentationKey: 'some-key'
}
};



angular service: clientAppSettings.service.ts :


clientAppSettings.service.ts


@Injectable()
export class ClientAppSettingService {
appUrl: string = "";
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.appUrl = baseUrl;
}
getConfig() {
return this.http.get<ClientAppSettings>(this.appUrl + 'api/ClientAppSettings');
}
}



backend controller:


namespace WebApp.Controllers
{
[Route("api/[controller]")]
public class ClientAppSettingsController : Controller
{
private readonly AppSettings _clientAppSettings;

public ClientAppSettingsController(IOptions<AppSettings> appSettings)
{
_clientAppSettings = appSettings.Value;
}

[HttpGet("[action]")]
public AppSettings Get()
{
return _clientAppSettings;
}
}
}



and appsetting.json:


appsetting.json


{
"AppConfig": {
"ApplicationInsights": {
"InstrumentationKey": "some-key"
}
}





Im not sure you can do this. Perhaps use a token replace in an environment.ts file at buildtime in some CI process possibly?
– nagrom97
Jun 29 at 9:25




2 Answers
2



You cant update the env file in runtime, its something that angular use in build time. Just save the setting in your service and pull them from there.



I don't think you can do it like you explained (https://github.com/angular/angular-cli/issues/2508). The environment files are used to set up some fixed variables for a specific environment.



If you want to store data from backend through your application you could use a shared service that holds the data.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift