How to import module to child module?
Asked Answered
L

2

6

I'm using ngx-translate in my Angular application. I'm import and done everything in app.module.ts:

import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
 }

@NgModule({
imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
        }
    })
],
bootstrap: [AppComponent]

@NgModule({
imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
        loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient]
        }
    })
],
bootstrap: [AppComponent]

I'm import and export modules like in example on github ngx-translate page. Translator works fine.

But I have subfolder which has his own module.ts file, pages.module.ts. When I want to using ngx-translate on html file in pages folder, i have information, that translate pipe is not recognize in this app. I think I need to import elements from app.module.ts to pages.module.ts. I tried, but i don't know how to do it.

Lava answered 2/11, 2018 at 14:37 Comment(2)
subfolder - is it an another angular app, or child of the main module?Paillasse
Child on the main module. app/app.module.ts and app/pages/pages.module.tsLava
P
15

Most likely you have to use TranslateModule.forChild (instead of TranslateModule.forRoot) in child module pages.module.ts.

In the child module use "extend" = true to get the settings from the root module

TranslateModule.forChild({
  extend: true
})
Paillasse answered 2/11, 2018 at 14:49 Comment(0)
I
-2

Create a shared module file (shared.module.ts)

import {HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
 }

@NgModule({
imports: [
TranslateModule.forRoot({
    loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
    }
})
], export: [TranslateModule]

Then import the shared module into any other module you want to use the Translate service in.

Intercalary answered 2/11, 2018 at 15:9 Comment(1)
Note: Never call a forRoot static method in the SharedModule. You might end up with different instances of the service in your injector tree. But you can use forChild if necessary. See official documentationBolero

© 2022 - 2024 — McMap. All rights reserved.