ngx-translate / core“错误:没有HttpClient的提供者!”

时间:2017-08-22 18:47:34

标签: angular ngx-translate

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

我一直在下面的屏幕截图中看到这些错误 Errors the popup in the browser console

我做错了什么?

1 个答案:

答案 0 :(得分:24)

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

有关详细信息,请参阅Difference between HTTP and HTTPClient in angular 4?