Reputation: 81
I am trying to use the APP_INITIALIZER in my root/app module to resolve the authenticated user from the API (PHP/Laravel). I don't want to store the user object in localStorage, so I just store the JWT token, and go get the user on page refresh. However, a feature module (lazy loaded) is loading before the promise returns from the service I created to run with the APP_INITIALIZER.
//app.module.ts
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { StartupService } from './startup.service';
...
export function initConfiguration(startupService: StartupService) {
return () => startupService.load();
}
@NgModule({
...
providers: [
StartupService,
{
provide: APP_INITIALIZER,
useFactory: initConfiguration,
multi: true,
deps: [StartupService]
},
],
...
//The startup.service.ts
import { Injectable, Injector } from '@angular/core';
import { AuthService } from 'app/core/auth.service';
@Injectable()
export class StartupService {
constructor(private injector: Injector) {}
load(): Promise<boolean> {
let auth = this.injector.get(AuthService);
if (auth.isAuthenticated()) {
auth.getLoggedInUser().subscribe(
response => {
//everything from here on is happening after app init
return Promise.resolve(true);
},
error => {
return Promise.reject(false);
}
);
} else {
return Promise.resolve(true);
}
}
}
Everything works and resolves, just not when I expect (I thought the APP_INITIALIZER resolves before any feature modules are loaded???
Upvotes: 7
Views: 11191
Reputation: 68665
Problem is that you can't return anything from the subscribe
function.
You can try something like this:
import { AuthService } from 'app/core/auth.service';
@Injectable()
export class StartupService {
constructor(private auth: AuthService) {}
load(): Promise<boolean> {
let promise = new Promise((resolve, reject) => {
if (auth.isAuthenticated()) {
auth.getLoggedInUser().subscribe(response => resolve(true),
error => reject(false));
} else {
resolve(true);
}
});
return promise;
}
}
Upvotes: 8