簡體   English   中英

如何在模塊組件中使用 ngx-translate?

[英]How to use ngx-translate in module components?

我正在研究 ngx-translate。 正如幾乎教程所描述的那樣,我將其用於 app.component.html 中。 但是如何在我的模塊的組件中做到這一點? 我是否有每個模塊的所有步驟,還是有更簡單的方法? 如果我將 app.module.ts 中的所有步驟帶到 my.module.ts,我會在運行 ng serve 時收到一條錯誤消息。

ERROR in src/app/landing-page/home/home.component.html:4:22 - error NG8004: No pipe found with name 'translate'.

這是我的 home.component.ts:

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  
  constructor(private translateServeice: TranslateService) { }

  ngOnInit(): void {
  }

}

這是我的landingpage.module.ts

  import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { HomeComponent } from './home/home.component';
    import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
    import { HttpClient, HttpClientModule } from '@angular/common/http';
    import { TranslateHttpLoader } from '@ngx-translate/http-loader';
    
    export function createTranslateLoader(http: HttpClient) {
      return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }
    
    @NgModule({
      declarations: [
        HomeComponent
      ],
      imports: [
        CommonModule,
        HttpClientModule,
        TranslateModule.forChild(
          {
            loader: {
              provide: TranslateLoader,
              useFactory: (createTranslateLoader),
              deps: [HttpClient]
            },
          }
        )
        
      ],
      exports: [
        HomeComponent
      ]
    })
    export class LandingPageModule { }

我錯過了模塊中的任何引用,還是我做錯了?

在模塊組件中使用 ngx-translate 的通常方法是什么?

[編輯]

這是我的演示項目: https://github.com/Christoph1972/angular-i18n-demo

請問有人可以展示如何運行它嗎?

只需將 TranslateModule 添加到組件模塊的導入中

或使導入導出TranslateModuleSharedTranslateModule添加到 app.module.ts 以導入

工作堆棧閃電戰

你好所有有同樣問題的人。 我一直在努力嘗試許多解決方案,但都沒有成功。 在我的情況下,我有一個導入translatemodule forchild的共享模塊,共享模塊被導入到使用延遲加載的應用程序的所有其他模塊中。 最后,我明白了為什么它對我不起作用。 這是我正在導入 translatemodule/sharemodule 的 position 它應該在commonmodule之后導入(@ngmodule 導入數組的第二個 position)。 在簡歷中:

  1. 確保在commonmodulebrowsermodule (在 appmodule 中)之后導入translatemodule

  2. 如果您使用延遲加載,請確保在此處導入translatemodule forchild

  3. 如果您有一個sharedmodule導入translatemodule forchild (就在commonmodule之后,如 1 )並在導出數組中添加 Translatemodule

在應用模塊中

  @NgModule({
  imports: [
    BrowserModule,
    TranslateModule.forRoot(),...

在 ngmodule 中的 sharedmodule 中
@NgModule({ 進口: [ CommonModule, TranslateModule.forChild(),.. 和出口

 exports: [LoaderComponent, NavBarComponent, TranslateModule],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM