代码之家  ›  专栏  ›  技术社区  ›  Willy

ngx translate/core“错误:HttpClient没有提供程序!”

  •  15
  • Willy  · 技术社区  · 7 年前

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

    {
        "HELLO": "Hi There"
    }
    

    我在下面的屏幕截图中不断发现这些错误 Errors the popup in the browser console

    1 回复  |  直到 7 年前
        1
  •  40
  •   Rahul Singh    7 年前

    ngx-translate/core 使用最新版本 HttpClientModule HttpModule 在中的imports数组中更改以下内容 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? 了解更多详细信息。