ranyeli
10/2/2017 - 8:01 PM

Right way to initialize a class/object from app.modulte.ts

Initialize a class object right away to use the values in all other classes that need them

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpModule, Http } from '@angular/http';
import { FormsModule } from '@angular/forms';


import { AppComponent } from './app.component';
import { SupplierComponent } from './components/supplier/supplier.component';

import { ApiCallService } from './service/apicall.service';
import { Resource } from './resources/resource';
import { PaginationComponent } from './components/pagination/pagination.component';

// use an exported function like this
export function getRs(rs: Resource) {
  // must return the method that sets the properties values using arrow syntax
  return () => rs.getResource();
}

@NgModule({
  declarations: [
    AppComponent,
    SupplierComponent,
    PaginationComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule
  ],
  providers: [
    ApiCallService,
    Resource,
    {
      provide: APP_INITIALIZER,
      useFactory: getRs,
      deps: [Resource], multi: true
    }],
  bootstrap: [AppComponent]
})
export class AppModule { }