注入服务以填充 environment.ts 文件中的值



我有一个angular服务(clientAppSettings.service.ts(。它从后端获取配置值,这是一个 json 文件 (appsettings.json(

我需要注入角度服务,以填充environment.ts文件中的值。因此,应从服务(clientAppSettings.service.ts(检索instrumentaionKey。任何指南都值得赞赏。

这是environmen.ts文件:

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

角度服务: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');
}
}

后端控制器:

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;
}
}
}

appsetting.json

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

您无法在运行时更新 env 文件,它在构建时会使用。只需将设置保存在服务中,然后从那里提取它们即可。

我认为你不能像你解释的那样做(https://github.com/angular/angular-cli/issues/2508(。环境文件用于为特定环境设置一些固定变量。

如果要通过应用程序存储后端的数据,可以使用保存数据的共享服务。

最新更新