Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - How to initialize data inside a service?

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?

like image 441
k.vincent Avatar asked Aug 10 '17 14:08

k.vincent


2 Answers

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.

like image 187
Lansana Camara Avatar answered Sep 29 '22 01:09

Lansana Camara


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

like image 25
Mark Avatar answered Sep 29 '22 00:09

Mark