I have some string constant value which has to be used in many components.I dont want to hard code or write them as strings in individual components. Where is the best place to maintain them in an angular2 application?
3 Answers
One of the solutions would be to place your string in a shared service. Inject the service in every component that need that property. This is specially good if your string is not a constant and the string value might be updated (but it's not your case, I guess).
An other way would be to declare a 'plain' typescript class, *.ts file, like so:
export const CONFIG = Object({
MYSTRING: 'Hello',
...
)}
Then use it in the component as (for example):
import { CONFIG } from 'shared/config';
myString = CONFIG.MYSTRING;
This is good to group all your constants in a single place.
You can also choose to go for a single constant:
export const MyString = "Hello";
and then you can import it in your component as the before.

- 27,856
- 27
- 95
- 103
There is no such thing called constant or config like angularJs 1 in angular.
So I would say to make a plane class and put all your string there. you can make them static so that directly with the class name you can access them.
export class StngsValue {
static finrstWord = 'this is test string';
static secoundWord = 'this is test string';
static thirdWord = 'this is test string';
}
Or you can put all your strings in a json file and call that josn file from a angular service like this
@Injectable()
export class ConfigService {
public config: any;
private configObs: Observable<any>;
constructor(private http: Http) {
}
public load(): Observable<any> {
if ( this.config ) {
return Observable.of(this.config);
} else {
this.configObs = this.http.get('/configuration.json').map((res) => {
this.config = this.config || res.json() || {};
return this.config;
});
}
return this.configObs;
}
}

- 20,520
- 23
- 96
- 132
you can use a shared service and make it a singleton so all your components are able to access the data/methods/etc from that service. so you just declare your file as
shared.service.ts
inside:
import { Injectable } from '@angular/core';
@Injectable()
export class SharedService{
public str: string;
}
in your app.module.ts import the service and in @ngModule, in providers add:
providers: [ SharedService ]
then in any of your components simply import the service, and in the component constructor, add:
constructor(public service: SharedService){}
here you are injecting the service into your component, you can read about dependecy injection
now you can access your string with this.service.string

- 978
- 10
- 25