Andy88
Andy88

Reputation: 767

Angular - How to set a dynamic environment variable?

I have an environment.ts like this:

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:

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

Example: In my account-component in the ngOnInit function I tried this:

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

I need to use the baseUrl to construct the url for the image profile.

It could work but sometimes the environment.baseImgUrl could be an empty string. what should be the best solution to valorize the environment variable before the loading of other components that will use that variable?

Upvotes: 0

Views: 2678

Answers (1)

yeMarn
yeMarn

Reputation: 36

It is better to use the state management or 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. 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.

Upvotes: 1

Related Questions