Angular 2 Global Constants Provider Injector Method

后端 未结 3 1988
谎友^
谎友^ 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 06:02

    import {Component} from 'angular2/core'
    import { Constants } from './constants'
    
    @Component({
        selector: 'test',
        template: `  
                        Constants: {{ urlTemplate }}
    
                  `
        providers:[Constants]
    
    })
    
    export class AppComponent{
    
      constructor(constants: Constants){
        this.urlTemplate = constants.root_dir;
      }
    
    }
    

    You can use adding Constants in providers:[Constants]


    The decorator @Injectable It is not necessary in this case, but Google recommends always use You can see here: https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#why-injectable-


    /*
    We recommend adding @Injectable() to every service class, even those that don't have dependencies and, therefore, do not technically require it. Here's why:
    Future proofing: No need to remember @Injectable when we add a dependency later.
    Consistency: All services follow the same rules, and we don't have to wonder why a decorator is missing
    */
    
    //@Injectable() 
    export class Constants{
      root_dir: string;
    
      constructor(){
          this.root_dir = 'http://google.com/'
        }
      }
    

    Plunker


    About @Inject used, you can read something here: what is the difference between using (@Inject(Http) http: Http) or not


    Now if you want this globally can add in bootstrap

    //main entry point
    import {bootstrap} from 'angular2/platform/browser';
    import {AppComponent} from './app';
    import { Constants } from './constants';
    
    
    bootstrap(AppComponent, Constants)
      .catch(err => console.error(err));
    

    //import { Injectable } from 'angular2/core'
    
    //@Injectable()
    export class Constants{
    root_dir: string;
    
      constructor(){
          this.root_dir = 'http://google.com/'
        }
      }
    

    import {Component, Inject} from 'angular2/core'
    import { Constants } from './constants';
    
    @Component({
        selector: 'test',
        template: `  
                        Constants: {{ urlTemplate }}
    
                  `
    
    })
    
    
    export class AppComponent{
    
      constructor(@Inject (Constants) constants: Constants){
        this.urlTemplate = constants.root_dir;
      }
    
    }
    

    Plunker

提交回复
热议问题