Angular 4/5/6 Global Variables

前端 未结 4 1913
孤城傲影
孤城傲影 2020-11-27 10:43

I really struggle with creating global variables in my Angular 2 application.

I already googled and read many posts on StackOverflow on this for the last 3 hours, h

4条回答
  •  广开言路
    2020-11-27 11:18

    I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

    1) Create environment variable in your environment.ts

    export const environment = {
        ...
        // runtime variables
        isContentLoading: false,
        isDeployNeeded: false
    }
    

    2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

    import { environment } from 'environments/environment';
    
    @Component(...)
    export class TestComponent {
        ...
        env = environment;
    }
    

    3) Use it in template...

    
    

    in *.ts ...

    env.isContentLoading = false 
    

    (or just environment.isContentLoading in case you don't need it for template)


    You can create your own set of globals within environment.ts like so:

    export const globals = {
        isContentLoading: false,
        isDeployNeeded: false
    }
    

    and import directly these variables (y)

提交回复
热议问题