简体   繁体   中英

Angular 5 How to load global variables from assets

In my angular 5 application I need to load some global variables like principal Url and some other stuff, I am following this example: github

So with this GET call in app.component:

 ngOnInit() {
    this.http.get('assets/config.json')
      .map(res => res.json())
      .toPromise()
      .then((config) => {
        // do stuff with the config
        console.log(config)
      });
  }

I can load all my variables, but now I am not sure that all the variables are loaded before I need them around the application.

Are there a way to achieve this, or some other way to load global variables? And is a good practice to create a file: global.ts to store all my variables providing it around my app?

Are there a way to achieve this, or some other way to load global variables? And is a good practice to create a file: global.ts to store all my variables providing it around my app?

Yes it is ! Create a file called globals.ts

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

@Injectable()
export class Globals {
  anyVariable: string = 'test';
}

Then just access it by importing it in your current component.

import { Globals } from './globals'

Don't forget to add the dependency injection in your app module like this

providers: [Globals]

You can access Globals entity from any point of your App via Angular dependency injection.

Having set of global variables is never a good idea but... it strongly depends on case of your project. When we are talking about using global variables you and your coworkers need to be one hundred percent sure what you are doing - for example make sure that your variable will not mutate state by someone else because application could crash. Here you have wiki - why global variables are bad idea Global Variables Are Bad - C2 Wiki

Let's come back to your angular case: You can easly create new typescript file where you will have your global variables. Remember to decorate your file with { Injectable } from '@angular/core'; than you have to import them to point where your application starts import { GlobalAssets } from './globalAssets ' . Register source in providers providers: [GlobalAssets ] . After all you can reference GlobalAssets in your components by IoC.

It can cause some problems and it is always better to register and read your necessary files ( configurations and other globals, like fetching necessary data from other endpoint ) before bootstraping application Reading data before application startup in Angular - not hundred percent sure how it was changed in Angular 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM