【问题标题】:ngx-translate don't find the urlngx-translate 找不到网址
【发布时间】:2017-10-10 21:32:39
【问题描述】:

我想在我的应用程序中翻译我的静态文本。运行应用程序后的输出在我的示例 TEST 中。就像我的变量的名称。我认为,问题是网址。只有像这个例子这样的完整网址有效,我不知道为什么。

我在 asp.core 2 上的 Angular 应用程序中使用了 ngx-translate。

我将 createTranslateLoader 函数放在我的 app.module.shared.ts 中。它由 app.module.browser.ts 和 app.module.server.ts 加载。

imports: [
        ...,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [Http]
            }
        }),...]

export function createTranslateLoader(http: Http) {
    console.log(http);
    return new TranslateHttpLoader(http, 'http://localhost:56601/i18n/', '.json');
}

我的默认语言是德语“de”。我把我的 de.json 放在 wwwroot/i18n/de.json 中。

最后一步我修改了我的 app.component.ts

   export class AppComponent {
        constructor(private translate: TranslateService
) {
            translate.addLangs(['en', 'de']);
            translate.setDefaultLang('de');
            translate.use('de');
            //let browserlang = translate.getBrowserLang();
            //translate.use(browserlang.match(/en|de/) ? browserlang : 'de');
        }

}

还有我的 app.component.html

<p style="color:wheat">{{ 'TEST' | translate }}</p>

我的 de.json 看起来像

{
  "TEST": "Deutscher Test"
}

【问题讨论】:

    标签: asp.net angular ngx-translate


    【解决方案1】:

    将 i18n 文件夹移至资产可能会解决您的问题。 然后还修改 createTranslateLoader:

    export function HttpLoaderFactory(http: Http) {
      return new TranslateHttpLoader(http, './assets/i18n/', '.json');
    }
    

    【讨论】:

    • 我试过了。现在我得到一个例外:通过服务器上的 Http 请求的 URL 必须是绝对的。网址:./assets/i18n/de.json。的完整路径是 wwwroot/assets/i18n/de.json
    • 尝试重构并使用 HttpClient 而不是 Http,如下所示:HttpLoaderFactory(http: HttpClient),然后在您的加载器中:{..., deps: [HttpClient] } 在 app.module 中提供以下导入语句:import { HttpClientModule, HttpClient } from '@angular/common/http';
    【解决方案2】:

    使用 ASPNET.Core 和 ngx-translate 对我来说以下工作正常

    export function translateLoaderFactory(http: Http) {
        return new TranslateStaticLoader(http, './i18n/', '.json');
    }
    

    我的资源文件和你的一样在 wwwroot/i18n/ 文件夹中。

    【讨论】:

    • 如果这不起作用,你能在网络选项卡中看到请求的资源 url 是什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多