What is the right way to share a constant variable across multiple Components and Services in Angular?
Eg: Consider a constant variable called CountryList which has an array of objects, having more than 250 values key value pairs.
How do I share this constant value in multiple angular components/services?
const CountryList = [
{name:'UK', value:'United Kingdom'},
{name:'USA', value:'United States of America'},
{name:'SG', value:'Singapore'},
...
]
First way (export from constants file)
countries.constants.ts
export const CountryList = [
{name:'UK', value:'United Kingdom'},
{name:'USA', value:'United States of America'},
{name:'SG', value:'Singapore'}
]
test.component.ts
import * as coutriesConstants from '../../shared/constants/countries.constants'
@Component(
...
countries = coutriesConstants.CountryList;
...
Second way (creating a service)
countries.service.ts
@Injectable({
providedIn: 'root',
})
export class CountriesService {
countryList = [
{name:'UK', value:'United Kingdom'},
{name:'USA', value:'United States of America'},
{name:'SG', value:'Singapore'}
]
}
test.component.ts
@Component(
...
constructor(public countriesSrv: CountriesService){}
// Now you can access the `countriesSrv.countryList` either in the ts file or in HTML
...
Third way (inject the value)
You can also inject the value like @jenson-button-event answered as well.
PS: I usually go with the service approach to avoid creating properties on every component I want to share my constant data & because that way my service will be injected through my components when I needed so, it will be a little more optimized. Also injecting the value has the same advantages but I find the service way more simple and easy to scale.