I'm developing an application with Angular, and my project supports multiple languages. I separated the admin routes from the app.module.ts file and created them in a different file. However, due to this separation, the translate service is not working on these pages. Here are my codes:
app.module.ts
@NgModule({
declarations: [
AppComponent,
AdminLayoutComponent
],
imports: [
BrowserAnimationsModule,
BrowserModule,
FormsModule,
HttpClientModule,
ComponentModule,
RouterModule,
AppRoutingModule,
NgxDatatableModule,
ButtonModule,
NgbModule,
ToastrModule.forRoot(),
// ngx-translate and the loader module
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http);
}
admin-layout.routing.ts
export const AdminLayoutRoutes: Routes = [
{ path: 'Configuration/:name',component: ConfigurationComponent, canActivate: [authGuard]},
{ path: 'Account/Change-Password',component: ChangePasswordComponent, loadChildren: () => ChangePasswordModule, canActivate: [authGuard]},
];
admin-layout.module.ts
@NgModule({
declarations: [
ConfigurationComponent,
ConfigurationSidebarComponent
],
imports: [
CommonModule,
RouterModule.forChild(AdminLayoutRoutes),
FormsModule,
NgbModule,
NgxDatatableModule,
AuthenticationModule,
ToastrModule.forRoot(),
TranslateModule.forRoot(),
ButtonModule,
SidebarModule
]
})
export class AdminLayoutModule { }
change-password.module.ts
@NgModule({
declarations: [
ChangePasswordComponent,
],
imports: [
CommonModule,
NgbModule,
FormsModule,
ReactiveFormsModule,
TranslateModule.forRoot(),
],
exports: [
ChangePasswordComponent,
]
})
export class ChangePasswordModule {
}
What is the reason for the translate service not working in admin routes, and how can I fix it? I want to learn the answers to these questions. I have done a lot of research on the internet and shared the code I tried, but none of them worked.
In App Component You already initialize TranslateModule with forRoot() method. If you need to import it in other module - import it in a normal way, without redundant forRoot(). It's purpose is to load it in a global way and You would like to initialize it only once, so You should change initialization in AdminLayoutModule, from TranslateModule.forRoot()
to TranslateModule
For further research: https://angular.io/guide/singleton-services