I have created a service simple service which loads at first a configuration from a JSON file. Because I want that the data is available when the app is started, I'm using the APP_INITIALIZER to load the data.
In the service itself the data is available and everything is fine. But when I use the service from inside a component it gets a strange behaviour. Please can somebody explain whats wrong with my code?
filterService.ts
export class FilterService {
url:string = '/admin2/src/assets/import.filter.json';
filters: Filter[];
currentFilter: Filter;
public loadFilters() {
this.http.get(this.url).subscribe(response => {
this.filters = <Filter[]>response;
if (this.filters[0])
this.currentFilter = this.filters[0];
});
}
this service is loaded during app init
app.module.ts
@NgModule({
...
providers: [
FilterService,
{ provide: APP_INITIALIZER, useFactory: (filterService: FilterService) => () => filterService.loadFilters(), deps: [FilterService], multi: true },
],
...
Finally, in my component I'm doing:
filter.component.ts
constructor(private filterService: FilterService) {}
ngOnInit() {
console.log('import initialized');
console.log(this.filterService);
console.log(this.filterService.currentFilter);
console.log(this.filterService.filters);
console.log(this.filterService.getFilters());
}
And now I really don't understand what is happen in the console.log
Object { http: {…}, url: "http://...} // as expected
undefined // ??
undefined // ??
undefined // ??
Why can't I access the object properties? It looks to me that everything is fine and available....
In your case =>
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { HttpClientModule } from "@angular/common/http";
import { FilterService } from './filter.service';
export function load_filters(filterService: FilterService) {
return () => filterService.loadFilters();
}
export function get_filters(filterService: FilterService) {
return () => filterService.getFilters();
}
@NgModule({
imports: [HttpClientModule],
providers: [
AppLoadService,
{ provide: APP_INITIALIZER, useFactory: load_filters, deps: [FilterService], multi: true },
{ provide: APP_INITIALIZER, useFactory: get_filters, deps: [FilterService], multi: true }
]
})
export class AppLoadModule { }
import { AppLoadModule } from './app-load/app-load.module';
@NgModule({
imports: [AppLoadModule]
})
I have followed this blog to create my APP_INITIALIZER => Please read it once(may be useful) https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.