使用Angular-universal

时间:2018-04-06 16:41:17

标签: angular angular5 angular-universal ngx-translate

我正在按如下方式配置ngx-translate:

翻译 - 服务器 - loader.service.ts

import {Observable} from "rxjs/Observable";
import {TranslateLoader} from '@ngx-translate/core';
import { Injectable,  Inject} from '@angular/core';

declare var require: any;

const fs = require('fs');

@Injectable()
export class TranslateServerLoader implements TranslateLoader {
    /**
     * Gets the translations from the server
     * @param lang
     * @returns {any}
     */
    public getTranslation(lang: string): Observable<any> {
        return Observable.create(observer => {
            observer.next(JSON.parse(fs.readFileSync(`i18n/${lang}.json`, 'utf8')));
            observer.complete();
        });
    }
}

app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import {makeStateKey, StateKey, TransferState} from '@angular/platform-browser';
import {TranslateServerLoader} from './translate-server-loader.service';


@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: TranslateServerLoader
      }
    })
  ],
  bootstrap: [AppComponent],
})

export class AppServerModule { }

app.module.ts

import { BrowserModule, BrowserTransferStateModule, TransferState } from '@angular/platform-browser';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { BetsComponent } from './bets/bets.component';
import { BetsEventComponent } from './bets-event/bets-event.component';
import { CountriesComponent } from './countries/countries.component';
import { InformationComponent } from './information/information.component';
import { JackpotComponent } from './jackpot/jackpot.component';
import { PromotionsComponent } from './promotions/promotions.component';
import { ResultComponent } from './result/result.component';
import { PromotionDetailsComponent } from './promotion-details/promotion-details.component';
import { TopFootballComponent } from './top-football/top-football.component';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { ClipboardModule } from 'ngx-clipboard';
import {TooltipModule} from 'primeng/primeng';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import {TranslateServerLoader} from './translate-server-loader.service';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';

import {
  MenuLeftComponent,
  FooterComponent,
  HeaderComponent,
  BetslipComponent,
  MenuBottomMobileComponent,
  SharedModule,
  FixtureService,
  BetslipService,
  TypeBetsService,
  TicketService,
  TimeService,
  PaginationService,
  TranslateTbet,
  CompetitionService,
  ResultService,
  NumberOnlyDirective
} from './shared';
import {
  CashierComponent,
  InPlayComponent,
  InboxComponent,
  LoginComponent,
  ProfileComponent,
  RegisterComponent,
  TicketsComponent,
  TicketWinLoseComponent,
  BetslipMobileComponent,
  CheckTicketsComponent,
  ContactUsComponent,
  CollapseComponent,
  CollapseModule,
} from './collapse';
import { CompetitionsComponent } from './competitions/competitions.component';

const rootRouting: ModuleWithProviders = RouterModule.forRoot([
  {path:'',component:HomeComponent},
  {path:'competitions/:id', component: CompetitionsComponent},
  {path:'match-bets/:idFixture', component: BetsEventComponent},
  {path:'results', component: ResultComponent},
  {path:'results/:nameLeague', component: ResultComponent},
  {path:'results/:nameLeague/:dateTime', component: ResultComponent},
  {path:'jackPot', component: JackpotComponent},
  {path:'promotions', component: PromotionsComponent},
  {path:'information/:idInformation', component:InformationComponent},
  {path:'promotionDetails', component: PromotionDetailsComponent},
  {path:'topFootball', component: TopFootballComponent},
  {path:'countries', component: CountriesComponent},
  {path:':id', component: BetsComponent},
], { useHash: false });

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    BetsComponent,
    BetsEventComponent,
    CountriesComponent,
    InformationComponent,
    JackpotComponent,
    PromotionsComponent,
    ResultComponent,
    PromotionDetailsComponent,
    TopFootballComponent,
    HeaderComponent,
    FooterComponent,
    MenuLeftComponent,
    BetslipComponent,
    MenuBottomMobileComponent,
    TicketWinLoseComponent,
    InPlayComponent,
    TicketsComponent,
      CheckTicketsComponent,
    LoginComponent,
    InboxComponent,
    RegisterComponent,
    CashierComponent,
    ProfileComponent,
    ContactUsComponent,
    BetslipMobileComponent,
    CollapseComponent,
    TranslateTbet,
    NumberOnlyDirective,
    CompetitionsComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    rootRouting,
    SharedModule,
    CollapseModule,
    HttpModule,
    HttpClientModule,
    BrowserTransferStateModule,
    BrowserModule.withServerTransition({
        appId: 'ng-universal-demystified'
    }),
    ClipboardModule,
    TooltipModule,
      TranslateModule.forRoot({
          loader: {
              provide: TranslateLoader,
              useFactory: HttpLoaderFactory,
              deps: [HttpClient]
          }
      })
  ],
  providers: [
    FixtureService,
    BetslipService,
    TypeBetsService,
    TicketService,
    TimeService,
    PaginationService,
    TranslateTbet,
    NumberOnlyDirective,
    CompetitionService,
    ResultService,
    TransferState,
    TranslateModule,
    TranslateServerLoader
  ],
  bootstrap: [AppComponent]
})

export class AppModule {
}

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
//    return new PruningTranslationLoader(http);
    return new TranslateHttpLoader(http);
}

使用命令编译perrfect:

npm run build

然后执行时:

node dist/server.js

在http:// localhost:8080运行服务器! ,但是当打开浏览器时,它在控制台中出现以下错误:

ERROR TypeError: Cannot read property 'getTranslation' of undefined
    at TranslateService.exports.TranslateService.TranslateService.getTranslation (/home/carlos/Proyectos/website/node_modules/@ngx-translate/core/bundles/core.umd.js:3168:54)
    at TranslateService.exports.TranslateService.TranslateService.retrieveTranslations (/home/carlos/Proyectos/website/node_modules/@ngx-translate/core/bundles/core.umd.js:3154:87)
    at TranslateService.exports.TranslateService.TranslateService.setDefaultLang (/home/carlos/Proyectos/website/node_modules/@ngx-translate/core/bundles/core.umd.js:3095:28)
    at new l (/home/carlos/Proyectos/website/dist/server.js:1:10949)
    at createClass (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:12477:20)
    at createDirectiveInstance (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:12322:37)
    at createViewNodes (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:13780:53)
    at createRootView (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:13669:5)
    at Object.createProdRootView [as createRootView] (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:14362:12)
    at ComponentFactory_.create (/home/carlos/Proyectos/website/node_modules/@angular/core/bundles/core.umd.js:11274:46)

**请,如果有人能帮助我,我将非常感激。 此致

1 个答案:

答案 0 :(得分:0)

TranslateServerLoader是类,而不是工厂。

尝试更改:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: TranslateServerLoader
  }
})

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useClass: TranslateServerLoader
  }
})