Reputation: 9662
What method can I use, in an Angular2 (using CLI and Webpack) project, to place common config data and parameters such as some api keys or API URLs? These parameters will be used by many components and services.
Our app is becoming pretty big and I try to find a solution to keep the app as light and efficient as possible.
Upvotes: 0
Views: 313
Reputation: 14087
You don't need to use a full-blown service or module just to store config data.
You could put your config info in a const
and expose the variable through dependency injection:
const SETTINGS = {
apiUrl: 'someUrl',
apiKey: 'someKey',
// ...
};
// Then, in your AppModule, declare the value for DI
@NgModule({
providers: [
{ provide: 'SETTINGS', useValue: SETTINGS },
// ...
]
})
Then, whenever you need to access the config (in a service or a component...), inject it:
import { Inject } from "@angular/core";
export class MyComponent {
constructor(@Inject('SETTINGS') private settings: any) {
}
}
The upside of this approach is that you can use different settings based on the environment, or whether you're running unit tests, etc.
Upvotes: 1