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!
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 {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With