如何在 angular 2 应用程序中制作 DateAdapter 单例?

问题描述:

我正在开发一个带有延迟加载模块的 angular 7 应用程序.我也在使用角材料组件.我想在 datepicker 组件中本地化和支持多种语言环境.

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.

当应用程序语言更改时,我想为整个应用程序全局更改它.它可以通过 DateAdapter.setLocale 方法完成.然而问题是,如果我在我的根模块上更改它,那么它不会在延迟加载的模块中更改.

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.

是的,延迟加载的模块有它们的注入器并接收它们的 DateAdapter,其中区域设置未设置为正确的.

Yes, lazy loaded modules have their injector and receive their DateAdapter, where locale is not set to the correct one.

如何在整个应用中实现 DateAdapter 是单例的?对于其他模块,有 forChild() 与 forRoot() API,但没有用于 datepicker 模块.

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.

我的问题是我在 SharedModule 中导入了 DateAdapter 然后导入了那个 SharedModule 在我的 AppModule 和其他 LazyModule 中.

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.

要使 DateAdapter 成为单例服务,您应该提供 DateAdapter 您只在应用程序的根级别使用一次,而不是在根级别和 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.

为此,请确保导入提供 DateAdapter 的模块,例如MatNativeDateModule,仅在您的 AppModule(或仅导入一次的其他根模块中,如 CoreModule).不要在多个模块中或在像 SharedModule 这样多次导入的模块中导入 MatNativeDateModule.

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 { }

然后您可以在 AppComponent 中设置区域设置.

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')
  }
}

并且具有设置区域设置的相同 DateAdapter 将注入您的 LazyModules.

And the same DateAdapter with the set locale will be injected in your LazyModules.