Angular 2 Global Constants Provider Injector Method

后端 未结 3 1993
谎友^
谎友^ 2021-02-20 05:36

I have a global constants like root directory that I want every component to have access to. In another stackoverflow question the answer was to create a constants class and imp

3条回答
  •  日久生厌
    2021-02-20 05:58

    To answer your questions:

    • All components using the Constants class will need to import your constants file.

    • In order to use the Constants class you need to inject it into the constructor of any consuming components, removing the injector.get() function from random.component.ts like so:

    export class App {
      constructor(constants: Constants) {
        this.url = constants.root_dir;
      }
    }
    

    You may also decorate your constant class as an @Injectable and @Inject it into the constructor of your component.

    Here is a working plunker.

    It is beneficial to bootstrap the shared constants at the app level so that only one instance of the class is created and shared among all components.

提交回复
热议问题