Angular2 - How to initialize data inside a service?

Viewed 16554

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?

2 Answers
Related