What is the best/recommended way to set a global constant to be used across the entire app, like an API URL string?
I have the JSON format and want to set a global constant and use across the entire app as a static.
import { Injectable } from '@angular/core';
@Injectable()
export class Service {
item_data = [
{ item_id:'1', item_image: "assets/img/bluesaphire.jpg",
item_title:'Blue Saphire Stone' }
];
Environment Variables can is a good way to handle this. See example:
https://medium.com/prototype-berlin/a-simple-way-to-use-environment-variables-in-ionic-3-12641dc55b55
Very Simple! Just follow these two steps -
1) Create an Injectable class (eg. AppConstants) in a root directory (eg. src) with required properties
2) Import it in your component class constructor & use wherever needed
So, your app.constants.ts would be like -
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
public class AppConstants {
public item_data = [
{ item_id:'1', item_image: "assets/img/bluesaphire.jpg", item_title:'Blue Saphire Stone' }
];
}
And, use it as -
// here, config is a directory & app.constants is a ts file
import { AppConstants } from '../../config/app.constants'; // update your way
public class TestComponent {
// dependency injection
constructor(private constants: AppConstants) { }
testMethod() {
// using it here
console.log(this.constants.item_data);
}
}