ngx-translate/core "Error: No provider for HttpClient!" ngx-translate/core“错误:未提供HttpClient!”

19
我已经下载了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"
}

我在屏幕截图中不断收到以下错误浏览器控制台弹出的错误信息

我做错了什么?


2
你的应用程序导入中缺少 HttpClientModule 模块。 - FAISAL
1个回答

45

这个 ngx-translate/core 使用最新的 HttpClientModule 而不是旧的 HttpModule,请在 NgModule 的导入数组中进行以下更改。

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

请查看Angular 4中HTTP和HTTPClient的区别?以获取更多详细信息。


1
太神奇了,只需添加“HttpClientModule”,它就像魔法一样正常工作了。来自哈利波特系列的魔法。 - Juan Vilar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接