user3547774
user3547774

Reputation: 1689

Angular2 DI accessing static properties

I have the following TS class

import { Injectable } from '@angular/core';

@Injectable()
export class Config {

    /**
     * [AuthServiceUrl description]
     * @type {string}
     */
    static AuthServiceUrl: string = 'http://localhost:3000';
}

Note the AuthServiceUrl is static. How can I access this property in Angular2s DI framework if I have something like this

constructor(private config: Config)

How do I access this. Plus if I want to make the Config class Singleton how do I do this in Angular2?

Upvotes: 1

Views: 682

Answers (1)

ranakrunal9
ranakrunal9

Reputation: 13558

To declare config variable and use it every where you can declare opaque-token as explained on https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#opaque-token.

Declare config interface and interface provider same as below :

=> config.ts

export interface Config {
  apiEndpoint: string;
}

export const CONFIG: Config = {
  apiEndpoint  : 'http://api.url.com'
};

=> config.provider.ts

import { OpaqueToken } from '@angular/core';
export let APP_CONFIG = new OpaqueToken('app.config');

Use it in some shared module as below :

=> shared.module.ts

import { NgModule } from '@angular/core';

import { CONFIG } from './config';
import { APP_CONFIG } from './config.provider';

@NgModule({
  providers : [
    {
      provide : APP_CONFIG,
      useValue: CONFIG
    }
  ]
})
export class SharedModule {}

Upvotes: 1

Related Questions