0

I have a small service to get my config.json: https://pastebin.com/GgWX7FaX

I want to use it in my component so I did

import { Config } from '../config/config';

@Component({
  selector: 'app-test',
  providers: [Config],

and

  constructor(private _config: Config) {
    this._config.load().then(() => {
      console.log(_config.get('test2')); // working
    });
     _config.get('test2'); // not working
  }

So, I want to load the configuration before the component constructor and be able to do this:

  constructor(private _config: Config) {
    var url = _config.get('apiUrl')
    var env = _config.getEnv('env')
  }

I found a solution that is sadly deprecated on : https://medium.com/@hasan.hameed/reading-configuration-files-in-angular-2-9d18b7a6aa4

eko
  • 39,722
  • 10
  • 72
  • 98
The Segfault
  • 939
  • 1
  • 10
  • 23
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – eko Apr 18 '17 at 09:23
  • No, sorry, I know why this is not working and the fact that the "not working code" doesn't work because it is asynchronous, I'm looking for an angular2 way to load the configuration file and pass it to my component before this component is initialized. someth such a componentResolver – The Segfault Apr 18 '17 at 09:27
  • 1
    If it's loaded asynchronously you don't have any other choice rather than to use it inside the callback. – eko Apr 18 '17 at 09:28
  • You can load asynchronous data before hand, this is a lot cleaner ^^ and their is a lot of choices such using router, providers or resolvers – The Segfault Apr 18 '17 at 09:36
  • 1
    So? use them :-) Your question is unclear.. You're just loading a config asynchronously and asking why it doesn't work outside of the then function. You should write a more specific answer. And if you are asking whether to use the router, provider or the resolver the answer is it depends and it will attract a lot of opinion based answers. – eko Apr 18 '17 at 09:39
  • Yeah you right, I'll try to implement one of those. Thanks ! – The Segfault Apr 18 '17 at 11:35

0 Answers0