My service retrieves essential data from the server for my components, but it should only be called once due to the heavy load it places on the server. I have encountered an issue where the service successfully fetches the data in the app module provider, as evidenced by logging, but when I try to access it in a component, it returns Undefined!
I attempted to optimize the service initialization by removing UserService from providers to avoid multiple initializations, but this approach led to errors.
The function responsible for fetching information:
getAdminInitInfo(): Promise<any> {
var vm = this;
const promise = this.http.get<AdminInit>(baseUrl + '/panel/admin/initial/')
.toPromise()
.then(
response => {
vm.adminInitInfo = response;
console.log(response);
}
)
return promise;
}
The factory intended for use in APP_INITIALIZATION:
export function adminProviderFactory(provider: UserService) {
return () => provider.getAdminInitInfo();
}
AppModule providers configuration:
providers: [
AuthGuardService,
AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
},
UserService,
{
provide: APP_INITIALIZER,
useFactory: adminProviderFactory,
deps: [UserService],
multi: true
}
]
Log output of the data retrieved in the component:
user.service.ts:23 service started
user.service.ts:23 service started
user.service.ts:70 {filters: {…}}
user.service.ts:78 undefined
overview.component.ts:19 undefined
Following this process, the adminInitInfo should be accessible whenever needed using this function:
getSomethingData() {
var data = {};
console.log(this.adminInitInfo);
if (!this.adminInitInfo) {
return undefined;
}
data['something'] = this.adminInitInfo.filters.something;
data['something2'] = this.adminInitInfo.filters.something2;
data['something3'] = this.adminInitInfo.filters.something3;
return data;
}
Usage example in a component:
ngOnInit() {
this.params = this.userService.getSomethingData();
}