0

I'm trying to implement ngx-translate from this tutorial:

Locally when I run the angular app using npm start it's working fine. But when I want to use custom subdir like this: ng build --output-path angular --base-href=/angular/ and to deploy it on Apache server.

File is located under src\assets\i18n\en.json

I get multiple errors like this:

message: "Http failure response for http://123.123.123.123/assets/i18n/en.json: 404 Not Found"

Do you know how this can be fixed?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808

2 Answers2

0

I use the following approach in an Angular 6 app, see if it helps you to find a solution:

app.module.ts

// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient);
}

const i18n_route = environment.production ? './assets/i18n/' : '../assets/i18n/';

export function createTranslateLoader(http: HttpClient) {
  return new TranslateHttpLoader(http, i18n_route, '.json');
}

  @NgModule({
  declarations: [
  ...
  ]
  imports: [
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      }
    }),
  ],
  ...
Fab2
  • 179
  • 1
  • 10
-1

Another approach is to use the LocationStrategy class from the @angular/common package. In that way it's possible to get the actual base href of the application.

export function HttpLoaderFactory(http: HttpClient, locationStrategy: LocationStrategy) {
  const loader = new TranslateHttpLoader(http);
  loader.prefix = `${locationStrategy.getBaseHref()}assets/i18n/`;
  return loader;
}



@NgModule({
declarations: [
...
]
imports: [
  TranslateModule.forRoot({
    loader: {
      provide: TranslateLoader,
      useFactory: HttpLoaderFactory,
      deps: [HttpClient, LocationStrategy],
    }
  }),
]

With the above approach, if your base-href is set to /angular, the assets path would be /angular/assets/i18n/

fuke
  • 1
  • 1
  • 1