Gibt es eine Möglichkeit für @Injectable
s als Singletons laden Komponenten mit loadChildren
(Lazy Loading Komponenten)?Angular2: Lazy laden Komponenten und Injektionen als Singletons
Wenn nicht, gibt es einen Weg, es zu bekommen?
Ich frage nach this post. Demnach ist es nicht möglich, @Injectable
als Singletons auf Submodulen zu injizieren.
Ich versuche, eine @Injectable AppState
als Singleton zu injizieren:
@Injectable()
export class AppState {
public user: string;
constructor() {
}
...
ich es auf AppModule
als provider
festgelegt haben:
// 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 habe ich schuf auch eine "submodule"
:
@NgModule({
//...
providers: [ AppState ]
})
export default class LoginModule {
Auf LoginComponent
ich tun:
export class Login implements OnInit {
constructor(private appState: AppState) {}
public doLogin():void {
this.appState.user = this.form.value.mail;
}
}
Trotzdem auf einer anderen Komponente Profile
genannt, es scheint, dass this.appState.user
nicht definiert ist.
@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
}
}
Warum this.appState.user
ist undifined wenn I'set es vor in einer anderen Komponente?
Stellen Sie es nicht auf der Ebene Ihrer Lazy Load _modules_ bereit. Sie müssen es auf dem 'app.module_level (oder wenn Sie einen in Ihrem' core.module' verwenden) angeben. –
Was ist mit [diesem Beitrag] (http://stackoverflow.com/a/40981772/217408)? – Jordi