首页 > 解决方案 > 注入服务以填充 environment.ts 文件中的值

问题描述

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

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

这是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"
        }
}

标签: angulartypescript

解决方案


您无法在运行时更新 env 文件,它在构建时有角度使用。只需将设置保存在您的服务中并从那里提取它们。


推荐阅读