问题
I'm developing an angular 7 application with lazy loaded modules. I'm using angular material components as well. I would like to localize and support multiple locales in datepicker component.
I would like to change it globally for the whole application when application language changes. It may be done via DateAdapter.setLocale method. However the problem is that if I change it on my root module then it does not change in lazy loaded modules.
Yes, lazy loaded modules have their injector and receive their DateAdapter, where locale is not set to the correct one.
How to achieve that DateAdapter is singleton in the whole app? For other modules there is a forChild() vs forRoot() API, but not for datepicker module.
回答1:
The problem for me was that I imported my DateAdapter
in my SharedModule
and then imported that SharedModule
in my AppModule
and in other LazyModules.
To make the DateAdapter
a singleton service you should provide the DateAdapter
you're using only once at root level in your application and not at root level and in LazyModules.
To do so make sure that you import the module that provides the DateAdapter
, e.g. MatNativeDateModule
, only in your AppModule
(or another root module thats imported only once like a CoreModule). Don't import MatNativeDateModule
in multiple modules or in a module that's imported multiple times like a SharedModule.
import { MatNativeDateModule } from '@angular/material/core'
@NgModule({
declarations: [
AppComponent,
],
imports: [
MatNativeDateModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Then you can set the locale in your AppComponent.
export class AppComponent implements OnInit {
constructor(private dateAdapter: DateAdapter<Date>) {}
ngOnInit(): void {
this.dateAdapter.setLocale('en')
}
}
And the same DateAdapter with the set locale will be injected in your LazyModules.
来源:https://stackoverflow.com/questions/53295457/how-to-make-dateadapter-singleton-in-angular-2-app