Angular2 - How to initialize data inside a service?
You could move your logic in the ngOnInit
in your service to the service's constructor. But even then, the link1
property may not be set immediately, so you may want to provide a default value for it.
But this seems like an antipattern to me. You can just use the native Angular 2 environment that is set up for you by default with Angular CLI.
It has both development/production variants and you can set your values in there however you want, and just import it in your service. Based on the way you do ng build
(if you pass -prod
flag or not), the different env variables will be used.
You can initialized your service at first by app initialization before using of the services.
That can be done with APP_INITIALIZER, see:
https://devblog.dymel.pl/2017/10/17/angular-preload/
Angular: How to correctly implement APP_INITIALIZER