@ngx-translate 在Nativescript/Angular 应用中的使用

4

我正在尝试创建一个基于ngx-translate(i18n)库的多语言NativeScript应用程序,我知道NPM上有几个其他插件,但它们都存在一些问题或不支持Angular 5,所以我决定使用这个库

我只是在nativescript-angular angular模板上创建了一个简单的应用程序,并将ngx-translate实现到我的项目中,并在应用程序根文件夹中设置了我的JSON文件

./assets/i18n/

但是一旦我运行我的项目,就会出现一些错误。

System.err: java.net.MalformedURLException: no protocol: ./assets/i18n/en.json

和其他错误

JS: ERROR Error: Uncaught (in promise): [object Object]

这是我在 Package.json 文件中的依赖项

"dependencies": {
    "@angular/animations": "~5.2.1",
    "@angular/common": "~5.2.1",
    "@angular/compiler": "~5.2.1",
    "@angular/core": "~5.2.1",
    "@angular/forms": "~5.2.1",
    "@angular/http": "~5.2.1",
    "@angular/platform-browser": "~5.2.1",
    "@angular/platform-browser-dynamic": "~5.2.1",
    "@angular/router": "~5.2.1",
    "@ngx-translate/core": "^9.1.1",
    "@ngx-translate/http-loader": "^2.0.1",
    "nativescript-angular": "~5.2.0",
    "nativescript-barcodescanner": "2.7.4",
    "nativescript-cardview": "2.0.5",
    "nativescript-fancyalert": "^1.1.2",
    "nativescript-feedback": "^1.1.0",
    "nativescript-google-maps-sdk": "^2.4.3",
    "nativescript-pro-ui": "~3.3.0",
    "nativescript-theme-core": "~1.0.4",
    "reflect-metadata": "~0.1.10",
    "rxjs": "~5.5.5",
    "tns-core-modules": "~3.4.0",
    "zone.js": "~0.8.18"
  },
  "devDependencies": {
    "@angular/compiler-cli": "~5.2.1",
    "@ngtools/webpack": "~1.9.1",
    "babel-traverse": "6.26.0",
    "babel-types": "6.26.0",
    "babylon": "6.18.0",
    "codelyzer": "~4.0.2",
    "copy-webpack-plugin": "~4.3.0",
    "css-loader": "~0.28.7",
    "extract-text-webpack-plugin": "~3.0.2",
    "lazy": "1.0.11",
    "nativescript-dev-sass": "~1.3.5",
    "nativescript-dev-typescript": "~0.6.0",
    "nativescript-dev-webpack": "~0.9.0",
    "nativescript-worker-loader": "~0.8.1",
    "raw-loader": "~0.5.1",
    "resolve-url-loader": "~2.2.1",
    "sass-loader": "~6.0.6",
    "tslint": "~5.9.1",
    "typescript": "~2.6.2",
    "uglifyjs-webpack-plugin": "~1.1.6",
    "webpack": "~3.10.0",
    "webpack-bundle-analyzer": "^2.9.1",
    "webpack-sources": "~1.1.0"
  }
}

这是我的app.module.ts文件

import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptModule } from "nativescript-angular/nativescript.module";


//Plugins
import { NSModuleFactoryLoader } from "nativescript-angular/router";
import { BarcodeScanner } from 'nativescript-barcodescanner';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';


import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";

import { NativeScriptHttpModule } from "nativescript-angular/http";
import { HttpClientModule, HttpClient } from '@angular/common/http';



import * as platform from "platform";
declare var GMSServices: any;

if (platform.isIOS) {
    GMSServices.provideAPIKey("XXX");
}

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

//Data service
// import { DataService } from './shared/dataService/dataService'

@NgModule({
    bootstrap: [
        AppComponent
    ],
    imports: [
        NativeScriptModule,
        AppRoutingModule,
        HttpClientModule,
        NativeScriptHttpModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [HttpClient]
            }
        })
    ],
    declarations: [
        AppComponent
    ],
    providers: [BarcodeScanner,
        { provide: NgModuleFactoryLoader, useClass: NSModuleFactoryLoader }
    ],
    schemas: [
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule { }

以及TranslateService文件

import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Component({
    selector: 'app',
    template: `
        <div>{{ 'HELLO' | translate:param }}</div>
    `
})
export class AppComponent {
    param = {value: 'world'};

    constructor(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');
    }
}

我在各个地方搜索,但是找不到基于@angular/common/http和ngx-translate以及NativeScriptHttpModule的Nativescript Angular 5应用程序的示例,能否有人帮助我,我真的很困惑,谢谢。


2
你找到解决方案了吗? - Royi Namir
1
@RoyiNamir,老兄,看看这个:https://discourse.nativescript.org/t/ngx-translate-nativescript-angular-application/4096 - akaco
3个回答

4

我使用Angular 7和NativeScript代码共享功能时,它可以正常工作。

你的示例中存在第一个问题,应该从路径中删除“.”。正确的路径为:

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

对于我来说,这解决了java.net.MalformedURLException的问题,但我还需要更改webpack配置来获取我的翻译文件(例如/assets/i18n/en.json),因此在您的webpack.config.js中修改此部分:
// Copy assets to out dir. Add your own globs as needed.
new CopyWebpackPlugin([
   { from: { glob: "fonts/**" } },
   { from: { glob: "**/*.json" } },
   { from: { glob: "**/*.jpg" } },
   { from: { glob: "**/*.png" } },
], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),

请查看我的GitHub代码库


我尝试实现您的解决方案,虽然我从路径中删除了'.',但仍然出现错误:“message”:“./assets/i18n/home/en.json的Http失败响应:0未知错误”您有任何想法为什么路径更改被忽略了吗? - MrfksIV
@MrfksIV 奇怪,您尝试过停止所有操作并重新构建吗(也许还需要删除“platforms”目录)? - Sebastian Denis
你的解决方案有效,我只是忘记在所有ngModules中进行更改。 - MrfksIV

2
ngx-translate工作中 "nativescript-angular": "~8.20.3",使用@danvick/ngx-translate-nativescript-loader插件(将访问JSON文件从HTTP修改为本地getFile)。

https://market.nativescript.org/plugins/@danvick%2Fngx-translate-nativescript-loader

请注意不要安装@ngx-translate/http-loader。如果使用http访问language.json将会出现错误,请使用上面提到的插件@danvick/ngx-translate-nativescript-loader从应用程序文件夹中获取语言json文件。将json文件直接放入assets文件夹中(参考我的示例),然后在app.module中进行设置。
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { NativeScriptLoader } from '@danvick/ngx-translate-nativescript-loader';
...
export function createTranslateLoader() {
    return new NativeScriptLoader("./assets/", ".json");
}

imports: [
        AppRoutingModule,
        NativeScriptModule,
        NativeScriptUISideDrawerModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: createTranslateLoader
            }
        }),

    ],

修改webpack.config.js文件,将“lang”.json复制到应用程序中(默认情况下,原生应用程序仅会将字体、png文件和jpg文件复制到应用程序资产文件夹中)。可以通过添加以下代码行来实现:{ from: { glob: "assets/**" } },其中语言JSON文件放置的位置(在i18n文件夹内或外)- 检查JSON文件是否已复制到platforms/ios|android/nameofapp/assets文件夹中。
new CopyWebpackPlugin([
                { from: { glob: "fonts/**" } },
                { from: { glob: "assets/**" } },
                { from: { glob: "**/*.jpg" } },
                { from: { glob: "**/*.png" } },
            ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }),

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接