0

I am new to Angualr 2 and RxJS (coming from Angular 1.x) and I am struggling with initializing the app properly.

Here is the scenario. My app needs some data from the server upon initializing. I was thinking of making an http call from the AppModule's constructor to retrieve this data, populate the service that will hold this data and then proceed with loading the app.

What is the best way to achieve this?

I tried using:

export class AppModule {
 constructor(http: Http, common: CommonService) {
  http.get('config').map(res => res.json()).do((cfg) => {
   common.config = cfg;
  });
 }
}

But the code in do(...) never executes.

Thanks.

dpdragnev
  • 2,011
  • 2
  • 28
  • 55
  • 1
    You can use `APP_INITIALIZER` for that http://stackoverflow.com/questions/37611549/how-to-pass-parameters-rendered-from-backend-to-angular2-bootstrap-method/37611614#37611614 it waits for promise or observable to complete before continuing app initialization. – Günter Zöchbauer Mar 10 '17 at 22:31
  • 1
    You always have to call subscribe on an observable, otherwise it won't execute. – Sebastian Mar 10 '17 at 22:40
  • Thank you @GünterZöchbauer. That did it. If you create an answer, I will accept it. – dpdragnev Mar 10 '17 at 23:05
  • Seems it currently only works with promise (not with observable) – Günter Zöchbauer Mar 11 '17 at 16:13
  • I have not tried using it with an Observable, but the Promise does the job. – dpdragnev Mar 13 '17 at 15:05
  • Ah! No! don't run code in your app module class. Everything should be in a service or component. In your case, put the call in your service's ngOnInit function. – wilsonhobbs Jun 03 '17 at 04:14

0 Answers0