Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load lists (http calls) on startup to application scope in Angular 5?

Tags:

angular

I'm looking to load data on startup, for example countries in using a LocationsService.

I'm implemented the current service:

...

@Injectable()
export class LocationsService {

  public countries: Country[];

  constructor(private http: HttpClient) {
  }

  public getCountries() {
    if (this.countries.length == 0) {
        this.http.get<Country[]>(`${this.url}`)
        .subscribe(data => { this.countries = data; },
            err => console.error(err),
            () => console.log(this.countries)
        )
    };
    return this.countries;
  }

}

I've tried to put the service inside the bootstrap:

bootstrap: [AppComponent, LocationsService]

But it doesn't work (raise an error actually). I need this type of lists to be available from startup (load 1 time only). Thanks!

like image 385
user2304483 Avatar asked Oct 17 '22 20:10

user2304483


1 Answers

use APP_INITIALIZER

first change your service instead of returning the data, return the Observable

@Injectable()
export class LocationsService {

  public countries: Country[];

  constructor(private http: HttpClient) {
  }

  public getCountries() {
    if (this.countries.length == 0) {
        return this.http.get<Country[]>(`${this.url}`);
    };
    return new Observable( c => {
      c.next(this.countries);
      c.complete();
   });
  }

}

create a service for setup

@Injectable()
export class SetupLocations {



  constructor(private loc: LocationsService ) {
  }

  public initliaze(): Promise<any> {
    return new Promise((resolve, reject) =>{
        this.loc.getCountries().subscribe((response) =>{

         //Do whatever you want here.

         //always call resolve method, because it will freeze your app.   
         resolve(true);

       }, (err) =>{});
     })
  }

}

next initialize it in your main module

import { NgModule, APP_INITIALIZER } from "@angular/core";



//create a function outside in the class module
export function SetupApp(setup: SetupLocations) {
    return () => setup.initliaze();
}



 @NgModule({
   providers: [
     SetupLocations,
     { 
        provide: APP_INITIALIZER,
        useFactory: SetupApp,
        deps: [SetupLocations],
        multi: true
     }]
})
export class AppModule {}
like image 102
John Velasquez Avatar answered Oct 21 '22 04:10

John Velasquez