Angular2 - How to initialize data inside a service?

k.vincent picture k.vincent · Aug 10, 2017 · Viewed 9.6k times · Source

I have two services. login.service.ts and environment-specific.service.ts.

In login.service.ts I need to initialize a Json object from environment-specific.service.ts which passes a couple of links.

The use case is how to make this working in the servcie without ngOnInit(){}, because ngOnInit() can't be used within a servcie as per Angular2 Lifecycle Hook.

Here you find the part I must initialize inside in login.service.ts - of course without ngOnInit() method:

...
import { EnvSpecific } from '../models/env-specific';
import { ActivatedRoute } from "@angular/router";

@Injectable()
export class LoginService {

   link1: string;
   link2: string;
   link3: string;

   constructor(private http: Http, private fbuilder:FormBuilder, private route: ActivatedRoute) { }

   ngOnInit(){
      this.route.data
         .subscribe((data: { envSpecific: EnvSpecific }) => {
            this.link1 = data.envSpecific.link1;
            this.link2 = data.envSpecific.link2;
            this.link3 = data.envSpecific.link3;
      });
   }
   ...
   ...
}

and I would like to pass the link(s) to the URL passed to different http.post API call. e.g:

...
var obsRequest = this.http.post( this.link1, serializedForm, this.options )
...

The Error is clear: link1 is undefined

Any suggestion or a hint please?

Answer

Lansana Camara picture Lansana Camara · Aug 10, 2017

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.