【问题标题】:ngx-translate/core "Error: No provider for HttpClient!"ngx-translate/core “错误:没有 HttpClient 的提供者!”
【发布时间】:2018-01-31 03:59:23
【问题描述】:

我已经下载了包 ngx-translate/core,并按照文档说明进行操作。

我无法进行翻译。 我做的步骤:

1] 在 AppModule 中定义所有内容

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { TranslateModule } from '@ngx-translate/core';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

import { routing } from './app.routes';

import { AppComponent } from './app.component';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}

    @NgModule({
     declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2] 在 AppComponent 中定义所有内容

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: []
})
export class AppComponent {
  param = { value: 'world' };

  constructor(private router: Router, translate: TranslateService) {
    // this language will be used as a fallback when a translation isn't found in the current language
    translate.setDefaultLang('en');

    // the lang to use, if the lang isn't available, it will use the current loader to get them
    translate.use('en');
  }
}

3] html

<div>{{ 'HELLO' | translate:param }}</div>

4] 最后在 assets/i18n/en.json 中创建

{
    "HELLO": "Hi There"
}

我在下面的屏幕截图中不断收到这些错误

我做错了什么?

【问题讨论】:

  • Yiu 在您的应用导入中缺少 HttpClientModule

标签: angular ngx-translate


【解决方案1】:

ngx-translate/core 使用最新的HttpClientModule 而不是旧的HttpModuleNgModule 的导入数组中更改以下内容

import { HttpClientModule } from "@angular/common/http";

  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule, // the change from http module
    routing,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ]

更多详情请见Difference between HTTP and HTTPClient in angular 4?

【讨论】:

    猜你喜欢
    • 2018-03-26
    • 2018-03-16
    • 2018-04-24
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2019-09-13
    • 2018-04-24
    相关资源
    最近更新 更多