Han Che Han Che - 1 year ago 100
TypeScript Question

how to load data into service on bootstrap in angular2 rc4

Here is the scenario. I have two services injected. I want ensure that some data e.g. a base url is passed to the first service so that all following service have access to it.

Here's my root component

export class AppCmp {

constructor (private httpService:HttpService, private SomeService:someService){}


here's the first service, lets assume it's a custom httpSerive

export class HttpService{
constructor(private http:Http){
getAll(){ return this.http.get(this.BASE_URL) }

here a second service, which will depend on the first one to perform a http.get request.

export class SomeService{
constructor(private httpSerivce:HttpSerivce){

I DONT want to hard code the base url (or data) into the service and I don't want to involve localStorages, so I have two options: either in the main.ts (bootstrap file) or root component, assuming they are separated.

The importance is that the data is available first thing and can be passed to or grabbed by the first injected service.

Hope I could illustrate the topic and thanks!

Answer Source

You can provide all kinds of value.

Register a provider using a string key (or an OpaqueToken)

{provide: 'BASE_URL', useValue: someUrl}

and inject it like

constructor(@Inject('BASE_URL') private baseURL:string)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download