How to implement class constants?

后端 未结 8 1863
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 17:40

In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with \"A class member cannot have the \'co

8条回答
  •  情深已故
    2020-12-22 18:24

    Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

    import { OpaqueToken } from "@angular/core";
    
    export let APP_CONFIG = new OpaqueToken("my.config");
    
    export interface MyAppConfig {
        apiEndpoint: string;
    }
    
    export const AppConfig: MyAppConfig = {    
        apiEndpoint: "http://localhost:8080/api/"    
    };
    

    Inject it in providers in app.module.ts

    You will be able to use it across every components.

    EDIT for Angular 4 :

    For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

    Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

    Example Code

    Angular 2 Using Opaque Tokens

    const API_URL = new OpaqueToken('apiUrl'); //no Type Check
    
    
    providers: [
      {
        provide: DataService,
        useFactory: (http, apiUrl) => {
          // create data service
        },
        deps: [
          Http,
          new Inject(API_URL) //notice the new Inject
        ]
      }
    ]
    

    Angular 4 Using Injection Tokens

    const API_URL = new InjectionToken('apiUrl'); // generic defines return value of injector
    
    
    providers: [
      {
        provide: DataService,
        useFactory: (http, apiUrl) => {
          // create data service
        },
        deps: [
          Http,
          API_URL // no `new Inject()` needed!
        ]
      }
    ]
    

    Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

提交回复
热议问题