Is there someway for providing @Injectable
s as singletons loading components using loadChildren
(lazy loading components)?
If not, is there some way to get it?
I'm asking it for this post. According to that, it's not possible to inject an @Injectable
as singletons on submodules.
I'm trying to inject an @Injectable AppState
as a singleton:
@Injectable()
export class AppState {
public user: string;
constructor() {
}
...
I've set it on AppModule
as provider
:
// Application wide providers
const APP_PROVIDERS = [
AppState
];
@NgModule({
bootstrap: [ App ],
declarations: [
App,
ErrorComponent
],
imports: [ // import Angular's modules
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(ROUTES, { useHash: true })
],
providers: [
APP_PROVIDERS
]
})
export class AppModule {
constructor(public appRef: ApplicationRef, public appState: AppState) {}
}
So, I've also created a "submodule"
:
@NgModule({
//...
providers: [ AppState ]
})
export default class LoginModule {
On LoginComponent
I do:
export class Login implements OnInit {
constructor(private appState: AppState) {}
public doLogin():void {
this.appState.user = this.form.value.mail;
}
}
Nevertheless, on another component named Profile
, it seems that this.appState.user
is undefined.
@NgModule({
//...
providers: [ AppState ]
})
export default class ProfileModule { /... }
@Component({
//...
})
export class Profile implements OnInit {
constructor(private appState: AppState) {
}
ngOnInit():void {
this.user = this.appState.user; <<<<<<<<<<<<< it's undefined
}
}
Why this.appState.user
is undifined if I'set it before in another component?