简体   繁体   English

Angular - 如何设置动态环境变量?

[英]Angular - How to set a dynamic environment variable?

I have an environment.ts like this:我有一个这样的environment.ts

export const environment = {
  production: false,
  // SERVER_API_URL: 'http://localhost:8080/',
  baseImgUrl: ``,
};

To initialize the baseImgUrl I need to call a service, and in the ngOnInit in the app.component.ts I do it:要初始化 baseImgUrl,我需要调用一个服务,并在ngOnInit中执行app.component.ts操作:

this.getImageUrl().subscribe(res => {environment.baseImgUrl = res.value});

But this is an async function and in other components I need to use these baseUrl for getting the userImage但这是一个异步函数,在其他组件中,我需要使用这些 baseUrl 来获取 userImage

Example: In my account-component in the ngOnInit function I tried this:示例:在我的ngOnInit函数中的account-component中,我尝试了以下操作:

this.getUserImageService().subscribe(res => { this.url = environment.baseImgUrl + res})

I need to use the baseUrl to construct the url for the image profile.我需要使用 baseUrl 来构建图像配置文件的 url。

It could work but sometimes the environment.baseImgUrl could be an empty string.它可以工作,但有时environment.baseImgUrl可能是一个空字符串。 what should be the best solution to valorize the environment variable before the loading of other components that will use that variable?在加载将使用该变量的其他组件之前,评估环境变量的最佳解决方案应该是什么?

It is better to use the state management or localStorage.最好使用状态管理或localStorage。 With state management, even if your image is updated in one component, it will be changed in other components as well.使用状态管理,即使您的图像在一个组件中更新,它也会在其他组件中更改。 You can check out the NGRX for state management library.您可以查看NGRX以获取状态管理库。 If you want to use localstorage, you need to have new variable for every component you want to show and you have to make localstorage.get('baseImageURL') in ngOninit() method of every component.如果你想使用localstorage,你需要为你想要显示的每个组件都有一个新的变量,你必须在每个组件的ngOninit()方法中创建localstorage.get('baseImageURL')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM