GithubHelp home page GithubHelp logo

ngx-translate / core Goto Github PK

View Code? Open in Web Editor NEW
4.5K 100.0 568.0 4.34 MB

The internationalization (i18n) library for Angular

License: MIT License

TypeScript 99.23% JavaScript 0.77%
angular i18n translation npm-package angular2 ngx ngx-translate

core's Introduction

@ngx-translate/core Build Status npm version

The internationalization (i18n) library for Angular.

Simple example using ngx-translate: https://stackblitz.com/github/ngx-translate/example

Get the complete changelog here: https://github.com/ngx-translate/core/releases

Table of Contents

Installation

First you need to install the npm module:

npm install @ngx-translate/core --save

Choose the version corresponding to your Angular version:

Angular @ngx-translate/core @ngx-translate/http-loader
16+ 15.x+ 8.x+
13+ (ivy only) 14.x+ 7.x+
10/11/12/13 13.x+ 6.x+
9 12.x+ 5.x+
8 12.x+ 4.x+
7 11.x+ 4.x+
6 10.x 3.x
5 8.x to 9.x 1.x to 2.x
4.3 7.x or less 1.x to 2.x
2 to 4.2.x 7.x or less 0.x

Usage

1. Import the TranslateModule:

Finally, you can use ngx-translate in your Angular project. You have to import TranslateModule.forRoot() in the root NgModule of your application.

The forRoot static method is a convention that provides and configures services at the same time. Make sure you only call this method in the root module of your application, most of the time called AppModule. This method allows you to configure the TranslateModule by specifying a loader, a parser and/or a missing translations handler.

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot()
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
SharedModule

If you use a SharedModule that you import in multiple other feature modules, you can export the TranslateModule to make sure you don't have to import it in every module.

@NgModule({
    exports: [
        CommonModule,
        TranslateModule
    ]
})
export class SharedModule { }

Note: Never call a forRoot static method in the SharedModule. You might end up with different instances of the service in your injector tree. But you can use forChild if necessary.

Lazy loaded modules

When you lazy load a module, you should use the forChild static method to import the TranslateModule.

Since lazy loaded modules use a different injector from the rest of your application, you can configure them separately with a different loader/compiler/parser/missing translations handler.

To make a child module extend translations from parent modules use extend: true. This will cause the service to also use translations from its parent module.

You can also isolate the service by using isolate: true. In which case the service is a completely isolated instance (for translations, current lang, events, ...). Otherwise, by default, it will share its data with other instances of the service (but you can still use a different loader/compiler/parser/handler even if you don't isolate the service).

@NgModule({
    imports: [
        TranslateModule.forChild({
            loader: {provide: TranslateLoader, useClass: CustomLoader},
            compiler: {provide: TranslateCompiler, useClass: CustomCompiler},
            parser: {provide: TranslateParser, useClass: CustomParser},
            missingTranslationHandler: {provide: MissingTranslationHandler, useClass: CustomHandler},
            isolate: true
        })
    ]
})
export class LazyLoadedModule { }
Configuration

By default, there is no loader available. You can add translations manually using setTranslation but it is better to use a loader. You can write your own loader, or import an existing one. For example you can use the TranslateHttpLoader that will load translations from files using HttpClient.

To use it, you need to install the http-loader package from @ngx-translate:

npm install @ngx-translate/http-loader --save

Once you've decided which loader to use, you have to setup the TranslateModule to use it.

Here is how you would use the TranslateHttpLoader to load translations from "/assets/i18n/[lang].json" ([lang] is the lang that you're using, for english it could be en):

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {HttpClientModule, HttpClient} from '@angular/common/http';
import {TranslateModule, TranslateLoader} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {AppComponent} from './app';

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

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }
AoT

If you want to configure a custom TranslateLoader while using AoT compilation or Ionic, you must use an exported function instead of an inline function.

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

@NgModule({
    imports: [
        BrowserModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: (createTranslateLoader),
                deps: [HttpClient]
            }
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

2. Define the default language for the application

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            defaultLanguage: 'en'
        })
    ],
    providers: [

    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

3. Init the TranslateService for your application:

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

4. Define the translations:

Once you've imported the TranslateModule, you can put your translations in a json file that will be imported with the TranslateHttpLoader. The following translations should be stored in en.json.

{
    "HELLO": "hello {{value}}"
}

You can also define your translations manually with setTranslation.

translate.setTranslation('en', {
    HELLO: 'hello {{value}}'
});

The TranslateParser understands nested JSON objects. This means that you can have a translation that looks like this:

{
    "HOME": {
        "HELLO": "hello {{value}}"
    }
}

You can then access the value by using the dot notation, in this case HOME.HELLO.

5. Use the service, the pipe or the directive:

You can either use the TranslateService, the TranslatePipe or the TranslateDirective to get your translation values.

With the service, it looks like this:

translate.get('HELLO', {value: 'world'}).subscribe((res: string) => {
    console.log(res);
    //=> 'hello world'
});

This is how you do it with the pipe:

<div>{{ 'HELLO' | translate:param }}</div>

And in your component define param like this:

param = {value: 'world'};

You can construct the translation keys dynamically by using simple string concatenation inside the template:

<ul *ngFor="let language of languages">
  <li>{{ 'LANGUAGES.' + language | translate }}</li>
</ul>

Where languages is an array member of your component:

languages = ['EN', 'FR', 'BG'];

You can also use the output of the built-in pipes uppercase and lowercase in order to guarantee that your dynamically generated translation keys are either all uppercase or all lowercase. For example:

<p>{{ 'ROLES.' + role | uppercase | translate }}</p>
role = 'admin';

will match the following translation:

{
  "ROLES": {
    "ADMIN": "Administrator"
  }
}

This is how you use the directive:

<div [translate]="'HELLO'" [translateParams]="{value: 'world'}"></div>

Or even simpler using the content of your element as a key:

<div translate [translateParams]="{value: 'world'}">HELLO</div>

6. Use HTML tags:

You can easily use raw HTML tags within your translations.

{
    "HELLO": "Welcome to my Angular application!<br><strong>This is an amazing app which uses the latest technologies!</strong>"
}

To render them, simply use the innerHTML attribute with the pipe on any element.

<div [innerHTML]="'HELLO' | translate"></div>

API

TranslateService

Properties:

  • currentLang: The lang currently used

  • currentLoader: An instance of the loader currently used (static loader by default)

  • onLangChange: An EventEmitter to listen to lang change events. A LangChangeEvent is an object with the properties lang: string & translations: any (an object containing your translations).

    example:

    onLangChange.subscribe((event: LangChangeEvent) => {
      // do something
    });
  • onTranslationChange: An EventEmitter to listen to translation change events. A TranslationChangeEvent is an object with the properties lang: string & translations: any (an object containing your translations).

    example:

    onTranslationChange.subscribe((event: TranslationChangeEvent) => {
      // do something
    });
  • onDefaultLangChange: An EventEmitter to listen to default lang change events. A DefaultLangChangeEvent is an object with the properties lang: string & translations: any (an object containing your translations).

    example:

    onDefaultLangChange.subscribe((event: DefaultLangChangeEvent) => {
      // do something
    });

Methods:

  • setDefaultLang(lang: string): Sets the default language to use as a fallback
  • getDefaultLang(): string: Gets the default language
  • use(lang: string): Observable<any>: Changes the lang currently used
  • getTranslation(lang: string): Observable<any>: Gets an object of translations for a given language with the current loader
  • setTranslation(lang: string, translations: Object, shouldMerge: boolean = false): Manually sets an object of translations for a given language, set shouldMerge to true if you want to append the translations instead of replacing them
  • addLangs(langs: Array<string>): Add new langs to the list
  • getLangs(): Returns an array of currently available langs
  • get(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>: Gets the translated value of a key (or an array of keys) or the key if the value was not found
  • getStreamOnTranslationChange(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>: Returns a stream of translated values of a key (or an array of keys) or the key if the value was not found. Without any onTranslationChange events this returns the same value as get but it will also emit new values whenever the translation changes.
  • stream(key: string|Array<string>, interpolateParams?: Object): Observable<string|Object>: Returns a stream of translated values of a key (or an array of keys) or the key if the value was not found. Without any onLangChange events this returns the same value as get but it will also emit new values whenever the used language changes.
  • instant(key: string|Array<string>, interpolateParams?: Object): string|Object: Gets the instant translated value of a key (or an array of keys). /!\ This method is synchronous and the default file loader is asynchronous. You are responsible for knowing when your translations have been loaded and it is safe to use this method. If you are not sure then you should use the get method instead.
  • set(key: string, value: string, lang?: string): Sets the translated value of a key
  • reloadLang(lang: string): Observable<string|Object>: Calls resetLang and retrieves the translations object for the current loader
  • resetLang(lang: string): Removes the current translations for this lang. /!\ You will have to call use, reloadLang or getTranslation again to be able to get translations
  • getBrowserLang(): string | undefined: Returns the current browser lang if available, or undefined otherwise
  • getBrowserCultureLang(): string | undefined: Returns the current browser culture language name (e.g. "de-DE" if available, or undefined otherwise

Write & use your own loader

If you want to write your own loader, you need to create a class that implements TranslateLoader. The only required method is getTranslation that must return an Observable. If your loader is synchronous, just use Observable.of to create an observable from your static value.

Example
class CustomLoader implements TranslateLoader {
    getTranslation(lang: string): Observable<any> {
        return Observable.of({KEY: 'value'});
    }
}

Once you've defined your loader, you can provide it in your configuration by adding it to its providers property.

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            loader: {provide: TranslateLoader, useClass: CustomLoader}
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Another custom loader example with translations stored in Firebase

How to use a compiler to preprocess translation values

By default, translation values are added "as-is". You can configure a compiler that implements TranslateCompiler to pre-process translation values when they are added (either manually or by a loader). A compiler has the following methods:

  • compile(value: string, lang: string): string | Function: Compiles a string to a function or another string.
  • compileTranslations(translations: any, lang: string): any: Compiles a (possibly nested) object of translation values to a structurally identical object of compiled translation values.

Using a compiler opens the door for powerful pre-processing of translation values. As long as the compiler outputs a compatible interpolation string or an interpolation function, arbitrary input syntax can be supported.

How to handle missing translations

You can setup a provider for the MissingTranslationHandler in the bootstrap of your application (recommended), or in the providers property of a component. It will be called when the requested translation is not available. The only required method is handle where you can do whatever you want. If this method returns a value or an observable (that should return a string), then this will be used. Just don't forget that it will be called synchronously from the instant method.

You can use useDefaultLang to decide whether default language string should be used when there is a missing translation in current language. Default value is true. If you set it to false, MissingTranslationHandler will be used instead of the default language string.

Example:

Create a Missing Translation Handler

import {MissingTranslationHandler, MissingTranslationHandlerParams} from '@ngx-translate/core';

export class MyMissingTranslationHandler implements MissingTranslationHandler {
    handle(params: MissingTranslationHandlerParams) {
        return 'some value';
    }
}

Setup the Missing Translation Handler in your module import by adding it to the forRoot (or forChild) configuration.

@NgModule({
    imports: [
        BrowserModule,
        TranslateModule.forRoot({
            missingTranslationHandler: {provide: MissingTranslationHandler, useClass: MyMissingTranslationHandler},
            useDefaultLang: false
        })
    ],
    providers: [

    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Parser

If you need it for some reason, you can use the TranslateParser service.

Methods:

  • interpolate(expr: string | Function, params?: any): string: Interpolates a string to replace parameters or calls the interpolation function with the parameters.

    This is a {{ key }} ==> This is a value with params = { key: "value" } (params) => \This is a ${params.key}` ==> This is a value with params = { key: "value" }

  • getValue(target: any, key: string): any: Gets a value from an object by composed key parser.getValue({ key1: { keyA: 'valueI' }}, 'key1.keyA') ==> 'valueI'

FAQ

I'm getting an error npm ERR! peerinvalid Peer [...]

If you're using npm 2.x, upgrade to npm 3.x, because npm 2 doesn't handle peer dependencies well. With npm 2 you could only use fixed versions, but with npm 3 you can use ^ to use a newer version if available.

If you're already on npm 3, check if it's an error (npm ERR!) or a warning (npm WARN!), warning are just informative and if everything works then don't worry !

If you're using an old version of Angular and ngx-translate requires a newer version then you should consider upgrading your application to use the newer angular 2 version. There is always a reason when I upgrade the minimum dependencies of the library. Often it is because Angular had a breaking changes. If it's not an option for you, then check the changelog to know which version is the last compatible version for you.

I want to hot reload the translations in my application but reloadLang does not work

If you want to reload the translations and see the update on all your components without reloading the page, you have to load the translations manually and call setTranslation function which triggers onTranslationChange.

Plugins

  • Localize Router by @meeroslav: An implementation of routes localization for Angular. If you need localized urls (for example /fr/page and /en/page).
  • .po files Loader by @biesbjerg: Use .po translation files with ngx-translate
  • browser.i18n Loader by @pearnaly: loader for native translation files of browser extensions.
  • ngx-translate-extract by @biesbjerg: Extract translatable strings from your projects
  • MessageFormat Compiler by @lephyrus: Compiler for ngx-translate that uses messageformat.js to compile translations using ICU syntax for handling pluralization, gender, and more
  • ngx-translate-zombies by @seveves: A vscode extension that finds unused translation keys and shows them in a diff view (so called zombies).
  • ngx-translate-multi-http-loader by @denniske: Fetch multiple translation files with ngx-translate.
  • ngx-translate-cache by @jgpacheco: Simplified version of localize-router. If you are already using localize-router you don't need this extension. This extension is aimed only to facilitate language caching.
  • ngx-translate-module-loader by @larscom: Fetch multiple translation files (http) with ngx-translate. Each translation file gets it's own namespace out of the box and the configuration is very flexible.
  • ngx-translate-all by @irustm: Automate translations for Angular projects.
  • ngx-translate-migrate by @irustm: Automate migrations from ngx-translate to Angular i18n.
  • ngx-translate-lint by @svoboda-rabstvo: Simple CLI tools for check ngx-translate keys in whole app
  • ngx-translate-cut by @bartholomej: Simple and useful pipe for cutting translations โœ‚๏ธ

Editors

  • BabelEdit โ€” translation editor for JSON files
  • Translation Manager โ€” Progressive web-app, translation editor for JSON files
  • Crowdl.io โ€” Free translation management and crowd-translations tool with support for JSON files
  • ngx-translate-editor - Simple GUI for CRUD translate files of ngx-translate, which included ngx-translate-lint
  • tl8.io - A multi-platform application to enable the whole product team, including non-developers, to modify translations. WYSIWYG interface. Results can be downloaded as JSON and copied in the project as is.

Extensions

VScode

  • Generate Translation by @thiagocordeirooo: A visual studio code extension for you to generate the translations without leaving the current file.
  • Lingua by @chr33z: A visual studio code extension to help managing translations for ngx-translate - featuring inline translation lookup and in-place translation creation and editing.

Additional Framework Support

core's People

Contributors

ailisobrian avatar aitboudad avatar alfonsserra avatar arnoabraham avatar badf00d avatar bartholomej avatar biesbjerg avatar chr33z avatar codeandweb avatar danielschuech avatar danielsogl avatar deeg avatar edd avatar egavard avatar greetclock avatar itekaf avatar jpinkster avatar juristr avatar maddeveloper avatar mlix8hoblc avatar nathanwalker avatar nglazov avatar nonameprovided avatar nsanitate avatar ocombe avatar ribizli avatar robwormald avatar saithis avatar samverschueren avatar wmaurer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

core's Issues

useStaticFilesLoader is not a function ?

Hi all,

I have a problem when use ng2-translate
This is my code

Boot.ts

import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {TRANSLATE_PROVIDERS, TranslateService, TranslatePipe, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';
import {Helper} from './utils/helper';
import {BaseHTTP} from './utils/baseHTTP';
import {App} from './app';

bootstrap(App, [
    ROUTER_PROVIDERS,
    HTTP_PROVIDERS, 
    TRANSLATE_PROVIDERS,
    TranslateService,
    Helper,
    BaseHTTP,
    provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

app.ts

import {Component, Injectable, provide} from 'angular2/core';
import {RouterOutlet, RouteConfig} from 'angular2/router';
import {Http} from 'angular2/http';
import {TranslateService, TranslatePipe, TranslateLoader, TranslateStaticLoader} from 'ng2-translate/ng2-translate';

@Injectable()
@Component({
    selector: 'main-app',
    templateUrl: './src/app/app.html',
    directives: [RouterOutlet],
    pipes: [TranslatePipe]
})
export class App {
    public translate;

    constructor(translate: TranslateService) {
        this.translate = translate;

        this.translationConfig();
    } 

    translationConfig() {
        var prefix = 'src/app/core/languages';
        var suffix = '.json';
        var userLang = 'en';
        this.translate.useStaticFilesLoader(prefix, suffix);
        this.translate.use(userLang);
    }  
}

And an error occurs this.translate.useStaticFilesLoader is not a function. But it work in last friday (4/3/2016) and today it don't work.
Please help me, thanks

Clarify which code belongs to which file

Especially for newcomers, it is hard to tell if you have to put some of the snippets to a component or service.

Additionally - Is it possible to setup the service once and use it in components and subcomponents?

Please update the documentation.

Thanks in advance.

getTranslation call does not have fallback mechanism

If call getTranslation for a language that does not have localized json file, there is no fallback mechanism to get the default language and it will throw angular 2 exception.
I also checked the fallback logic inside get by key function in source code. The fallback mechanism seems not correct as well. It assumes that the default language has been loaded which is not the case all the time. It probably should try to send a request to get it if it is not in cache.

Error: Cannot read property 'getOptional' of undefined(โ€ฆ)

I have tried the ng2-translate, but I at runtime when it tries to use TranslateService:

/// <reference path="../../../../../../node_modules/angular2/platform/browser.d.ts"/>
import {bootstrap}    from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {HomeControllerApp} from './component-home-controller-app';

bootstrap(HomeControllerApp, [
    HTTP_PROVIDERS,
    TranslateService
]);```

it throws an error:

```Error: Cannot read property 'getOptional' of undefined(โ€ฆ)run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:1444(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305```

package.json dependencies:

"devDependencies": {
"grunt": "~0.4.5",
"grunt-cli": "~0.1.13",
"grunt-contrib-copy": "~0.8.1",
"i18next-client": "~1.11.0",
"jquery": "~2.2.0",
"knockout": "~3.4.0",
"log4js": "~0.6.27",
"requirejs": "~2.1.20",
"sockjs": "~0.3.15",
"typescript": "^1.7.3"
},
"dependencies": {
"bootstrap": "3.3.5",
"font-awesome": "4.5.0",
"angular2": "2.0.0-beta.0",
"es6-promise": "3.0.2",
"es6-shim": "0.33.13",
"ng2-translate": "1.7.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"systemjs": "0.19.6",
"zone.js": "0.5.13"
}

Peer Dependency

Its a bit similar to #37.

I want to update to angular 2 beta 7. They ve updated RXjs to beta 2. They depend on version two and you peer dependency depend on beta 0. So i cant resolve this on my own. I would recommend to set peer dependency to ~beta.0. Then you can support different versions of angular 2 and the developer needs to resolve the peer dependency by his own.

Greetings,
Daniel

problems when unit testing applications that use this lib

https://github.com/ocombe/ng2-translate/blob/master/src/translate.service.ts#L4-L6

Should not include '.js'
Causes karma issues like:

01 02 2016 16:37:38.185:WARN [web-server]: 404: /base/node_modules/rxjs/add/observable/fromArray.js.js
01 02 2016 16:37:38.187:WARN [web-server]: 404: /base/node_modules/rxjs/add/operator/share.js.js
01 02 2016 16:37:38.192:WARN [web-server]: 404: /base/node_modules/rxjs/add/operator/map.js.js
01 02 2016 16:37:38.447:WARN [web-server]: 404: /base/node_modules/rxjs/add/observable/fromArray.js.js
01 02 2016 16:37:38.447:WARN [web-server]: 404: /base/node_modules/rxjs/add/operator/share.js.js
01 02 2016 16:37:38.448:WARN [web-server]: 404: /base/node_modules/rxjs/add/operator/map.js.js

[ionic2] EXCEPTION: No provider for Http! (MyApp -> TranslateService -> Http)

Hi,

I'm having similar issue like someone else had with its Project. Mine was Ionic2 (2.0.0-alpha.49), ng2-translate (1.3.0) and angular2 (2.0.0-beta.0- yes, beta0 since ionic2 relies on it.

EXCEPTION: No provider for Http! (MyApp -> TranslateService -> Http)BrowserDomAdapter.logError @ browser_adapter.js:76BrowserDomAdapter.logGroup @ browser_adapter.js:86ExceptionHandler.call @ exception_handler.js:56(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430collection_1.StringMapWrapper.merge.onError @ ng_zone.js:325run @ zone-microtask.js:123(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$$internal$$tryCatch @ zone-microtask.js:1493lib$es6$promise$$internal$$invokeCallback @ zone-microtask.js:1505lib$es6$promise$$internal$$publish @ zone-microtask.js:1476(anonymous function) @ zone-microtask.js:225microtask @ ng_zone.js:383run @ zone-microtask.js:120(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$asap$$flush @ zone-microtask.js:1287
browser_adapter.js:76 STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.js:76ExceptionHandler.call @ exception_handler.js:58(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430collection_1.StringMapWrapper.merge.onError @ ng_zone.js:325run @ zone-microtask.js:123(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$$internal$$tryCatch @ zone-microtask.js:1493lib$es6$promise$$internal$$invokeCallback @ zone-microtask.js:1505lib$es6$promise$$internal$$publish @ zone-microtask.js:1476(anonymous function) @ zone-microtask.js:225microtask @ ng_zone.js:383run @ zone-microtask.js:120(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$asap$$flush @ zone-microtask.js:1287

And another exception:

Error: DI Exception
    at NoProviderError.BaseException [as constructor] (exceptions.js:15)
    at NoProviderError.AbstractProviderError [as constructor] (exceptions.js:38)
    at new NoProviderError (exceptions.js:74)
    at Injector._throwOrNull (injector.js:851)
    at Injector._getByKeyDefault (injector.js:902)
    at Injector._getByKey (injector.js:842)
    at Injector._getByDependency (injector.js:828)
    at Injector._instantiate (injector.js:720)
    at Injector._instantiateProvider (injector.js:711)
    at Injector._new (injector.js:700)BrowserDomAdapter.logError @ browser_adapter.js:76ExceptionHandler.call @ exception_handler.js:59(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430collection_1.StringMapWrapper.merge.onError @ ng_zone.js:325run @ zone-microtask.js:123(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$$internal$$tryCatch @ zone-microtask.js:1493lib$es6$promise$$internal$$invokeCallback @ zone-microtask.js:1505lib$es6$promise$$internal$$publish @ zone-microtask.js:1476(anonymous function) @ zone-microtask.js:225microtask @ ng_zone.js:383run @ zone-microtask.js:120(anonymous function) @ ng_zone.js:343zoneBoundFn @ zone-microtask.js:93lib$es6$promise$asap$$flush @ zone-microtask.js:1287

I've injected ng2-translate as this:

import {HTTP_PROVIDERS} from 'angular2/http';
import {TranslateService} from 'ng2-translate/ng2-translate';
import {
  App,
  IonicApp,
  Platform,
  Config,
  NavController,
  NavParams
} from 'ionic/ionic';
import {News} from './pages/News/News';

@App({
  templateUrl: 'build/app.html',
  config: {},
  providers: [HTTP_PROVIDERS, TranslateService]

})

export class MyApp {
  constructor(
    platform: Platform,
    app: IonicApp,
    translate: TranslateService
  ) {
  ...

Help me out (if possible) ๐Ÿ‘

SystemJs compatibility and bundle distribution

We have few problems integrating your library.
The first is the compatibility with SystemJs......second we don't have any "bundle" file.

For the first we use tsconfig.json with:

 "target": "es5"
 "module": "system",

So we actually get always Uncaught ReferenceError: require is not defined.

For the second problem we are developing a solution using Visual Studio 2015 and we have node_modules directory outside "wwwroot" so we have to move files directly into a folder named libs inside wwwroot. For example we have the "angular2.dev.js" file ...now we really need to have a single bundled file to be used otherwise it will be a "mess"....i guess.
What do you think?

Feature: fallback language

As requested in #15:

It would also be great to specify a fallback language in config. So if your app is in English but is mostly translated to Japanese then you could fallback to English.

Update to angular2.0.0-alpha.53

I need a version compatible with angular2.0.0-alpha.53.
Now you have fix on package.json "angular2": "2.0.0-alpha.52", as dependency

angular2-polyfills.js:1243 Error: TypeError: Cannot read property 'getOptional' of undefined

After I have upgraded from 1.7.3 to 1.10.0, my's app boostrap throws an error:

bootstrap(HomeControllerApp, [
    HTTP_PROVIDERS,
    ROUTER_BINDINGS,
    // TRANSLATE_PROVIDERS,
    provide(TranslateLoader, { // it works if I comment this provide function
        useFactory: (http: Http) => new TranslateStaticLoader(http, "locales", "/translation.json"),
        deps: [Http]
    }),
    // TranslateService,
    provide(LocationStrategy, { useClass: HashLocationStrategy })

]);
angular2-polyfills.js:1243 Error: TypeError: Cannot read property 'getOptional' of 
undefined(โ€ฆ)

Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @   angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback   @   angular2-polyfills.js:480
lib$es6$promise$$internal$$publish  @   angular2-polyfills.js:451
lib$es6$promise$$internal$$publishRejection @   angular2-polyfills.js:401
(anonymous function)    @   angular2-polyfills.js:123
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @   angular2-polyfills.js:262
Mutation (async)        
(anonymous function)    @   angular2-polyfills.js:237
asap    @   angular2-polyfills.js:191
scheduleMicrotask   @   angular2-polyfills.js:129
(anonymous function)    @   angular2-polyfills.js:122
lib$es6$promise$$internal$$fulfill  @   angular2-polyfills.js:411
lib$es6$promise$$internal$$resolve  @   angular2-polyfills.js:392
resolvePromise  @   angular2-polyfills.js:516
a   @   system.js:4
i.onreadystatechange    @   system.js:4
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
XMLHttpRequest.send (async)     
N   @   system.js:4
(anonymous function)    @   system.js:4
lib$es6$promise$$internal$$initializePromise    @   angular2-polyfills.js:515
lib$es6$promise$promise$$Promise    @   angular2-polyfills.js:806
(anonymous function)    @   system.js:4
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:4
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @   angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback   @   angular2-polyfills.js:480
lib$es6$promise$$internal$$publish  @   angular2-polyfills.js:451
(anonymous function)    @   angular2-polyfills.js:123
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @   angular2-polyfills.js:262
Mutation (async)        
(anonymous function)    @   angular2-polyfills.js:237
asap    @   angular2-polyfills.js:191
scheduleMicrotask   @   angular2-polyfills.js:129
(anonymous function)    @   angular2-polyfills.js:122
lib$es6$promise$$internal$$fulfill  @   angular2-polyfills.js:411
lib$es6$promise$$internal$$resolve  @   angular2-polyfills.js:392
resolvePromise  @   angular2-polyfills.js:516
a   @   system.js:4
i.onreadystatechange    @   system.js:4
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
XMLHttpRequest.send (async)     
N   @   system.js:4
(anonymous function)    @   system.js:4
lib$es6$promise$$internal$$initializePromise    @   angular2-polyfills.js:515
lib$es6$promise$promise$$Promise    @   angular2-polyfills.js:806
(anonymous function)    @   system.js:4
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:5
(anonymous function)    @   system.js:4
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @   angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback   @   angular2-polyfills.js:480
lib$es6$promise$$internal$$publish  @   angular2-polyfills.js:451
(anonymous function)    @   angular2-polyfills.js:123
Zone.run    @   angular2-polyfills.js:1243
zoneBoundFn @   angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @   angular2-polyfills.js:262

original working dependencies:

"dependencies": {
    "bootstrap": "3.3.5",
    "font-awesome": "4.5.0",
    "angular2": "2.0.0-beta.0",
    "es6-promise": "3.0.2",
    "es6-shim": "0.33.13",
    "ng2-translate": "1.7.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "systemjs": "0.19.6",
    "zone.js": "0.5.13"
  }

after upgrade:

"dependencies": {
    "bootstrap": "3.3.5",
    "font-awesome": "4.5.0",
    "angular2": "2.0.0-beta.9",
    "es6-promise": "3.0.2",
    "es6-shim": "0.35.0",
    "ng2-translate": "1.10.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "systemjs": "0.19.24",
    "zone.js": "0.5.15"
  }

TranslatePipe markForCheck - needs to happen on init as well?

The fix works great when using OnPush after a value has changed. However I'm seeing that the pipe does not transform anything when everything initializes/bootstraps from the start.

You can see this on this branch:
https://github.com/NathanWalker/angular2-seed-advanced/tree/on-push

Clone and checkout that branch, then:

npm install
npm start

You'll see that no text is translated on page to start, however if you change the language dropdown in top right, it will then fire change detection and then the pipe will transform and show all the text.

I would submit a PR to fix, but not sure what needs to be done. @ocombe hoping you know :)

Including ts source file inside npm package would be problematic

Hey,

I upgraded to v1.6.4 and the new version includes ts source files inside npm package. And I found that my typescript compiler would actually try to compile the ts files. With this version, the typescript compiler is actually messing up with the output path since it considered the folder contains node_modules folder is the root folder which is actually not.

I also took a look at the npm package structure of angular 2. They did not have ts files along with those d.ts files. And the main d.ts file would only export other d.ts files not ts files.

I am wondering if you guys can change the structure of bundled npm package?

Thanks.

Loading Translation Files Per Entry-Point?

Sorry if this isn't quite the right forum for this, but I'm working on what will become a really large project and am splitting it into different entrypoints / webpack bundles. It's possible a user with access to module A might not have access to module B, or that a deployment for a particular customer might not even include module C.

Is there a (recommended) way to split lang.json files on a module level with this plugin? Would I call
translate.useStaticFilesLoader(prefix, suffix); multiple times?

Better to include them in the module TypeScript and use set(key: string, value: string, lang?: string): so that it's part of what webpack bundles for that module anyway?

Exception if translation key is missing

If a translation key is missing in a language, that is not set as defaultLang I get following exception:

TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at step (http://localhost:5555/node_modules/ng2-translate/src/translate.parser.js:37:20)
    at Parser.flattenObject (http://localhost:5555/node_modules/ng2-translate/src/translate.parser.js:48:9)
    at TranslateService.getParsedResult (http://localhost:5555/node_modules/ng2-translate/src/translate.service.js:199:46)
    at TranslateService.get (http://localhost:5555/node_modules/ng2-translate/src/translate.service.js:229:52)

It seems that the code is trying to access the key of the default language as a fallback, without loading the language file.

I am not sure how to handle it. Maybe it is a good idea to remove the fallback and add the ability to return a string in the MissingTranslationHandler.

using in project

Hi,

I'm trying to integrate this library in the starter kit provided by AngularClass:
https://github.com/AngularClass/angular2-webpack-starter.

PatrickJS/PatrickJS-starter#208

The webpack dev server is serving from the src folder. The translations are defined in
src/assets/i18n.

It doesn't seem to find the translation files using the provided setup:

export class App {
  name = 'Angular 2 Webpack Starter';
  url = 'https://twitter.com/AngularClass';
  constructor(translate: TranslateService) {

    var prefix = 'assets/i18n';
    var suffix = '.json';
    translate.useStaticFilesLoader(prefix, suffix);

    var userLang = navigator.language.split('-')[0]; // use navigator lang if available
    userLang = /(nl|fr|en)/gi.test(userLang) ? userLang : 'en';

    // optional, default is "en"
    translate.setDefaultLang('en');

    // the lang to use, if the lang isn't available, it will use the current loader to get them
    translate.use(userLang);

  }
}

But if I change the configuration to be var prefix = 'src/assets/i18n'; it works.

I'm not sure this is something related to your package or perhaps to the starter kit architecture. So that's why I'll post it and reference it in both projects.

Kr
Sam V.

Remove *.ts files from src during publishing to npm.

During compilation I have the errors

error TS6059: File '../node_modules/ng2-translate/src/translate.parser.ts' is not under 'rootDir' '../src'. 'rootDir' is expected to contain all sou
rce files.
error TS6059: File '../node_modules/ng2-translate/src/translate.pipe.ts' is not under 'rootDir' '../src'. 'rootDir' is expected to contain all sourc
e files.
error TS6059: File '../node_modules/ng2-translate/src/translate.service.ts' is not under 'rootDir' '../src'. 'rootDir' is expected to contain all so
urce files.

Configuration:

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "noImplicitAny": true,
    "declaration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "noEmitHelpers" : true,
    "rootDir" : "src",
    "outDir" : "tmp/es5"
  },

  "exclude": [
    ".git",
    "node_modules",
    "tmp"
  ]
}

This is because ng2-translate.d.ts is importing from folder src where there are .d.ts and .ts files, and ts files are loading by default by tsc.

angular2 have a different approach where ts sources are in ts folder.

After removing .ts files from src everything works fine.

SystemJS cant find ng2-translate when using the Angular 2 quickstart setup

Hey,
at first I like to say that I appreciate your affords. Until now I haven't found anything about i18n in Angular 2, even though they promised it as a feature. So: Thx!

I got a project, which uses pretty much the same setup, as in the Angular 2 quickstart tutorial.
I followed your install instructions, but SystemJS is not looking at the node_modules folder.
I expect to load ng2-translate from /node_modules/ng2-translate/ng2-translate.js but the browser is requesting /ng2-translate/ng2-translate.js

I made a repository, which reproduces the error https://github.com/fr3dm4n/ng2Quickstart-beta.0/tree/ng-translate

It may be my fault,but you could help other ng2-SystemJs rookies as well ;)

Problem in Unit Test Environment

I written an wrapper arround ng2-translate to perfectly fit my use cases. While testing i dont want to test only my wrapper that it just call your correct functions.

So my function calls translateService.use. The lang isn't available so getTranslation is called. There you load them and subscribe to the pending observable. In this subscription you are going to delete this.pending. This is my problem.

I ve a very similar testing setup like you. The only change is located in the answering of MockBackend conenctions. You are going to save them and answering them when you call your mockBackendResponse function. I will answer them directly when they appear.
So the Observable wil lbe resolvewd directly and the subscription will executed directly before the use function can subscribe to this.pending. This.pending is deleted and i got the following error:

TypeError: Cannot read property 'subscribe' of undefined
        at TranslateService.use (/.../node_modules/ng2-translate/src/translate.service.js:90:20)

The error seems to be correct thorugh my test environment.

My Question is why are you going to delete this.pending? I removed it and all your tests passes and I could find any problems while running ng2-translate. So is it possible to remove line 134 in translate.service.ts?

Greetings,
Daniel

Angular2 Beta 10 peer dependencies

I'm trying to install Angular2 Beta 10 and latest ng2-translate (1.10.1)

Seems like ng2 wants zone.js ^0.6.4 while ng2-translate wants zone.js ^0.5.10

npm ERR! Linux 3.13.0-79-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install"
npm ERR! node v0.12.12
npm ERR! npm v2.14.9
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants zone.js@^0.6.4
npm ERR! peerinvalid Peer [email protected] wants zone.js@^0.5.10

No provider for TranslateLoader!

I am using ng2-translate to localize my ionic 2 app, But i am getting this runtime exception
1 175606 group EXCEPTION: No provider for TranslateLoader! (MyApp -> TranslateService -> TranslateLoader) 2 175607 error EXCEPTION: No provider for TranslateLoader! (MyApp -> TranslateService -> TranslateLoader) 3 175607 error STACKTRACE: 4 175607 error Error: DI Exception at NoProviderError.BaseException [as constructor] (http://localhost:8101/build/js/app.bundle.js:7706:24) at NoProviderError.AbstractProviderError [as constructor] (http://localhost:8101/build/js/app.bundle.js:8402:17) at new NoProviderError (http://localhost:8101/build/js/app.bundle.js:8438:17) at Injector._throwOrNull (http://localhost:8101/build/js/app.bundle.js:6745:20) at Injector._getByKeyDefault (http://localhost:8101/build/js/app.bundle.js:6796:22) at Injector._getByKey (http://localhost:8101/build/js/app.bundle.js:6736:26) at Injector._getByDependency (http://localhost:8101/build/js/app.bundle.js:6722:26) at Injector._instantiate (http://localhost:8101/build/js/app.bundle.js:6613:37) at Injector._instantiateProvider (http://localhost:8101/build/js/app.bundle.js:6603:26) at Injector._new (http://localhost:8101/build/js/app.bundle.js:6592:22)

Here is how i am using it:
`import {App, Platform} from 'ionic-angular';
import {TabsPage} from './pages/tabs/tabs';
import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';

// https://angular.io/docs/ts/latest/api/core/Type-interface.html
import {Type} from 'angular2/core';

@app({
template: '<ion-nav [root]="rootPage">',
config: {},
providers: [TranslateService],
pipes: [TranslatePipe]
})
export class MyApp {
rootPage: Type = TabsPage;
translate;

constructor(platform: Platform, translate: TranslateService) {
    this.translate = translate;

    platform.ready().then(() => {
        console.log(navigator.language.split('-')[0]);
          this.initializeTranslateServiceConfig();
    });
}

initializeTranslateServiceConfig() {
    var prefix = 'assets/i18n/';
    var suffix = '.json';
    this.translate.useStaticFilesLoader(prefix, suffix);
    var userLang = navigator.language.split('-')[0];
    userLang = /(de|en|hr)/gi.test(userLang) ? userLang : 'en';
    this.translate.setDefaultLang('en');
    this.translate.use(userLang);
}

}
`
Please help in finding why i have this error,

Detailed documentation for methods

It is unclear if you have to use useStaticFilesLoader in conjunction with getTranslation.
Which is required and where (!) see #27.

It is unclear which path is used for the useStaticFilesLoader. Relative to directory of execution? Relative to file? Absolute?

Any additions to the documentation and a less vague description of the methods would be very much appreciated.

Thanks in advance.

Upgrade version 1.2.5 problem

EXCEPTION: No provider for Http! (App -> TranslateService -> Http)
browser_adapter.js:76EXCEPTION: No provider for Http! (App -> TranslateService -> Http)BrowserDomAdapter.logError @ browser_adapter.js:76BrowserDomAdapter.logGroup @ browser_adapter.js:86ExceptionHandler.call @ exception_handler.js:56(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430errorHandling.onError @ ng_zone.js:328run @ core.js:99(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$$internal$$tryCatch @ es6-promise.js:326lib$es6$promise$$internal$$invokeCallback @ es6-promise.js:338lib$es6$promise$$internal$$publish @ es6-promise.js:309(anonymous function) @ microtask.js:37microtask @ ng_zone.js:383run @ core.js:96(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$asap$$flush @ es6-promise.js:120
browser_adapter.js:76STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.js:76ExceptionHandler.call @ exception_handler.js:58(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430errorHandling.onError @ ng_zone.js:328run @ core.js:99(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$$internal$$tryCatch @ es6-promise.js:326lib$es6$promise$$internal$$invokeCallback @ es6-promise.js:338lib$es6$promise$$internal$$publish @ es6-promise.js:309(anonymous function) @ microtask.js:37microtask @ ng_zone.js:383run @ core.js:96(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$asap$$flush @ es6-promise.js:120
browser_adapter.js:76Error: DI Exception
at NoProviderError.BaseException as constructor
at NoProviderError.AbstractProviderError as constructor
at new NoProviderError (exceptions.js:74)
at Injector._throwOrNull (injector.js:852)
at Injector._getByKeyDefault (injector.js:903)
at Injector._getByKey (injector.js:843)
at Injector._getByDependency (injector.js:829)
at Injector._instantiate (injector.js:721)
at Injector._instantiateProvider (injector.js:712)
at Injector._new (injector.js:701)BrowserDomAdapter.logError @ browser_adapter.js:76ExceptionHandler.call @ exception_handler.js:59(anonymous function) @ application_ref.js:183NgZone._notifyOnError @ ng_zone.js:430errorHandling.onError @ ng_zone.js:328run @ core.js:99(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$$internal$$tryCatch @ es6-promise.js:326lib$es6$promise$$internal$$invokeCallback @ es6-promise.js:338lib$es6$promise$$internal$$publish @ es6-promise.js:309(anonymous function) @ microtask.js:37microtask @ ng_zone.js:383run @ core.js:96(anonymous function) @ ng_zone.js:343zoneBoundFn @ core.js:69lib$es6$promise$asap$$flush @ es6-promise.js:120
bootstrap.ts:18NoProviderError {message: "No provider for Http! (App -> TranslateService -> Http)", stack: "Error: DI Exceptionโ†ต at NoProviderError.BaseExcโ€ฆttp://127.0.0.1:8899/build/common.js:9511:22)", keys: Array[3], injectors: Array[3]}


note๏ผšV 1.2.4 is OKใ€‚

Getting error while incorporating ng2-translate.

    System.config({
        packages: {
            assets: {
                format: 'register',
                defaultExtension: 'js'
            }
        },
        map: {
            moment: 'node_modules/moment/moment.js',
            'ng2-translate': 'node_modules/ng2-translate'
        }

    });
    System.import('assets/main')
            .then(null, console.error.bind(console));

This is my system.config script, and I got error on browser's console is

  1. Uncaught (in promise) TypeError: object is not a constructor
    at then (native)
  2. angular2-polyfills.js:1243 SyntaxError: Unexpected token <
    Evaluating http://localhost:3000/node_modules/ng2-translate/ng2-translate
    Error loading http://localhost:3000/assets/main.js
    at SystemJSLoader.__exec (http://localhost:3000/node_modules/systemjs/dist/system.src.js:1395:16)
    at entry.execute (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3521:16)
    at linkDynamicModule (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3126:32)
    at link (http://localhost:3000/node_modules/systemjs/dist/system.src.js:2969:11)
    at Object.execute (http://localhost:3000/node_modules/systemjs/dist/system.src.js:3301:13)
    at doDynamicExecute (http://localhost:3000/node_modules/systemjs/dist/system.src.js:703:25)
    at link (http://localhost:3000/node_modules/systemjs/dist/system.src.js:905:20)
    at doLink (http://localhost:3000/node_modules/systemjs/dist/system.src.js:557:7)
    at updateLinkSetOnLoad (http://localhost:3000/node_modules/systemjs/dist/system.src.js:605:18)
    at http://localhost:3000/node_modules/systemjs/dist/system.src.js:417:11

Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:468
lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:480
lib$es6$promise$$internal$$publish @ angular2-polyfills.js:451
lib$es6$promise$$internal$$publishRejection @ angular2-polyfills.js:401
(anonymous function) @ angular2-polyfills.js:123
Zone.run @ angular2-polyfills.js:1243
zoneBoundFn @ angular2-polyfills.js:1220
lib$es6$promise$asap$$flush @ angular2-polyfills.js:262

Systemjs + typescript import

Hi,

Thanks for your works on this library.
I try to load it from Systemjs/jspm without using gulp or other build tools just the plugin-typescript https://github.com/frankwallis/plugin-typescript

I add this package instruction to my config.js
"ng2-translate": { "defaultExtension": "ts", "meta": { "*.ts": { "loader": "ts" } } }

I import with:

import {TranslateService} from 'ng2-translate/ng2-translate'

But i have got this exception:

Uncaught SyntaxError: Unexpected token = translate.service.ts:179 Uncaught SyntaxError: Unexpected token = @ system.src.js:4892(anonymous function) @ system.src.js:4892(anonymous function) @ system.src.js:4892(anonymous function) @ system.src.js:4892 Uncaught SyntaxError: Unexpected token = Evaluating http://localhost:3000/dist/bundle.js Error loading http://localhost:3000/dist/bundle.js Error loading http://localhost:3000/app/app.ts

Any idea ?

Julie.

useStaticFilesLoader() throws TypeError

I modified your ng2-play fork to use the static file loader. It throws the following error:

angular2.js:23514 EXCEPTION: Error during instantiation of HelloApp!.BrowserDomAdapter.logError @ angular2.js:23514BrowserDomAdapter.logGroup @ angular2.js:23525ExceptionHandler.call @ angular2.js:1145(anonymous function) @ angular2.js:14801NgZone._notifyOnError @ angular2.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:23514 ORIGINAL EXCEPTION: TypeError: this.http.get(...).map is not a functionBrowserDomAdapter.logError @ angular2.js:23514ExceptionHandler.call @ angular2.js:1154(anonymous function) @ angular2.js:14801NgZone._notifyOnError @ angular2.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:23514 ORIGINAL STACKTRACE:BrowserDomAdapter.logError @ angular2.js:23514ExceptionHandler.call @ angular2.js:1157(anonymous function) @ angular2.js:14801NgZone._notifyOnError @ angular2.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:23514 TypeError: this.http.get(...).map is not a function
    at TranslateStaticLoader.getTranslation (translate.service.ts:40)
    at TranslateService.getTranslation (translate.service.ts:119)
    at TranslateService.use (translate.service.ts:99)
    at new HelloApp (hello.js:36)
    at angular2.js:1376
    at Injector._instantiate (angular2.js:11920)
    at Injector._instantiateProvider (angular2.js:11859)
    at Injector._new (angular2.js:11849)
    at InjectorInlineStrategy.instantiateProvider (angular2.js:11609)
    at ElementInjectorInlineStrategy.hydrate (angular2.js:13234)BrowserDomAdapter.logError @ angular2.js:23514ExceptionHandler.call @ angular2.js:1158(anonymous function) @ angular2.js:14801NgZone._notifyOnError @ angular2.js:5796collection_1.StringMapWrapper.merge.onError @ angular2.js:5700run @ angular2-polyfills.js:141(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243microtask @ angular2.js:5751run @ angular2-polyfills.js:138(anonymous function) @ angular2.js:5719zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305Promise.resolve (async)(anonymous function) @ angular2-polyfills.js:235asap @ angular2-polyfills.js:1232scheduleMicrotask @ angular2-polyfills.js:250(anonymous function) @ angular2-polyfills.js:242lib$es6$promise$$internal$$fulfill @ angular2-polyfills.js:1454lib$es6$promise$$internal$$resolve @ angular2-polyfills.js:1435resolvePromise @ angular2-polyfills.js:1559load @ system.src.js:1017xhr.onreadystatechange @ system.src.js:1026run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111XMLHttpRequest.send (async)fetchTextFromURL @ system.src.js:1049(anonymous function) @ system.src.js:1555lib$es6$promise$$internal$$initializePromise @ angular2-polyfills.js:1558lib$es6$promise$promise$$Promise @ angular2-polyfills.js:1849(anonymous function) @ system.src.js:1554(anonymous function) @ system.src.js:2446(anonymous function) @ system.src.js:3011(anonymous function) @ system.src.js:3244(anonymous function) @ system.src.js:3840(anonymous function) @ system.src.js:4031(anonymous function) @ system.src.js:4277(anonymous function) @ system.src.js:326run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$$internal$$tryCatch @ angular2-polyfills.js:1511lib$es6$promise$$internal$$invokeCallback @ angular2-polyfills.js:1523lib$es6$promise$$internal$$publish @ angular2-polyfills.js:1494(anonymous function) @ angular2-polyfills.js:243run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111lib$es6$promise$asap$$flush @ angular2-polyfills.js:1305
angular2.js:23514 ERROR CONTEXT:

[HELP] Translate urls

Hi and thanks for the plugin, works great in template

Is it possible and could you show an exemple of how you would translate urls ?

Say we have a route defined this way :

{ path: '/login', component: LoginFormCmp, as: 'Login' }

Since translate.get returns an observable i cannot figure a way to do it

Thanks

Missing Translation Handler

A MissingTranslationHandler can be set up in angular-translate while the config phase.

I would like to have something similar in ng2-translate. As I ve seen your code I would think that this would be no problem to be added. If you would accept that feature I could provide a PR.

Example Use Case:
The requested Key isnt available in the translation. In the dev mode of your application it would call a http get to a specific route. On the serverside you can add the not existing key to your translation file. So you can just use new keys and add the translations later without missing a key.

parser.flattenObject is called too often

As the language definition JSON object can get complex, it is a performance penalty to always flatten this JSON, any time a translate.get (or translate.instant) is called.

I'd recommend the other way: parsing the key (split by dot) and try to address the JSON field recursively.

E.g. (just a dummy demonstration):

let key = 'keyA.keyB.keyC';
let keys = key.split('.');
let value;
try {
  value = obj;
  for (let i = 0; i < keys.length; i++) {
    value = value[key[i]];
  }
} catch (e) {
  value = '!!!not found';
}

use interface instead of abstract class MissingTranslationHandler

It is much easier (more flexible) to implement an interface than extend a class in Typescript. MissingTranslationHandler has no added value being a an abstract class.

(I'd also check TranslateLoader for the same, but it has a play with DI, where class might be desirable)

Ionic2-Meteor integration

I have an Angular2-Meteor project using the barbatus:ionic2-meteor package for Ionic2.

I have successfully used the ng2-translate module with a regular Ionic2 app, but I'm having trouble getting it to work in a meteor project (v1.2.1). I do not know how use the SystemJS module loader to load npm modules for use in the project. I keep getting Cannot find module 'ng2-translate/ng2-translate'

How do I configure my Meteor project to use the ng2-translate module?

Cannot access the nested JSON Object

I am facing an issue, when i am using single string value in JSON it works, but when using object instead it doesn't works, below is the code explained.

   translate.setDefaultLang('en');

    translate.setTranslation('en', {
        "helloWorld": {
             "sayHello": "Hello there!"
         },
         "helloWorldSayHello": "Hello there!"
    });

    this.translate.use('en');
    <div>{{ 'helloWorldSayHello' | translate }} world</div> ----------//this does work
    <div>{{ 'helloWorld.sayHello' | translate }} world</div> ----------//this doesn't work

Is their any other way to make it work?

Webpack loading, not finding files.

Hey, I'm using webpack to load my TS files and it spits out some errors when I load this package.
screen shot 2016-02-16 at 2 46 25 pm

I'm including the file like this

import {TranslateService} from 'ng2-translate';

and my webpack TS-loader configuration looks a little something like this

{ test: /\.ts$/, loader: 'ts-loader', exclude: [ /\.(spec|e2e|async)\.ts$/ ] },

I'm relatively new to typescript, and I imagine this has something to do with typings? Do I need to do anything special typings wise for this package?

Please define another method for Instant string retrieval

angular-translate had such a good method which you could use in JS (not in templates) without getting a Promise back.

$translate.instant('key') would then return you your value of key in lang file.

where as current translate (from ng2-translate) always returns observable. There are few parts in my code, where I would just want to call translate.instant(key) without making a long .subscribe(data =>... part.

Could that kind of function be also implemented in ng2-translate?

Thank you for your work!

๐Ÿ‘

Feature: "instant" translateService method, e.g. synch translations

Hi, I've just started using the library but I'm trying to use dynamic values (i.e. belonging to the component ).
I've checked the angular-translate library and I've seen it's possible pass in the filter a scope reference, but I don't want to pollute my component logic.
So I created an helper method which takes in the key and the values object, but the translationService, at the moment, it always returns an Observer, which means you have to use the async pipe in the template.

{{ utils.getLocalisedString("MONETARY.NO_SENT_TITLE", { value: mycomponentValue}) }}

I've looked into angular-translate and I've refactored the code in 10 minutes for a basic "instant" method, which returns synchronously the interpolated string (in my app, I've made sure the language is always preloaded, so the sync approach fits my case).

How would you deal with this scenario?

Thanks,
M.

unknown function bootstrap, incorrect order

Hello there!

I just started out to develop with Angular2.
Currently I'm extending an existing project to implement ng2-translate and I just can't get it to work.

First of all, the method bootstrap does not exist. It doesn't get imported from any of your calls either. So.. I have no idea about it. More information on that would be appreciated,

Second - How can you use TranslateService before you import it? Thats not going to work AFAIK.

Any help to resolve this issue is very much appreciated.

import {Component, OnInit, Injectable} from 'angular2/core';
import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router';
import {FORM_PROVIDERS} from 'angular2/common';
import {HTTP_PROVIDERS} from 'angular2/http';
import {TranslateService, TranslatePipe} from 'ng2-translate/ng2-translate';

Using translations within html attribute

I don't get this seem to work, using Ionic2 and ng2-translate.

<ion-refresher pullingText="{{ 'Pull to refresh...' | translate }}">

Getting error:

EXCEPTION: SyntaxError: Unexpected token }

Is there a way to fix this? Thank you for all the help.

Re-evaluation of translate pipes if ChangeDetectionStrategy.OnPush is set

Hi,

I am currently try to use ChangeDetectionStrategy.OnPush in all my components. That means, that all bindings are not checked if the state of my application stays the same. Thats great but it means that all translate pipes are not getting re-evaluated if I change the current language.

I think It may possible to wrap the pipe into an own directive that listens to the onLangChange event and invalidates itself.

Do you have any Ideas?

can I use this library with the UpgradeAdapter

I tried to use this library with the angular2 UpgradeAdapter. But I get the following error when I try to add it: TypeError: Cannot read property 'toString' of undefined

I tried the following
upgradeAdapter.addProvider(TRANSLATE_PROVIDERS);

Could someone provide a working sample. Thankx!

this.onLangChange.emit is not a function

Hi,

Using ng2-translate 1.7.0 i have the followinf error when I set language :
"this.onLangChange.emit is not a function"

The bug doesn't stop angular executing or translater job.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.