Use translateProvider.useLoader with Typescript

4k views Asked by At

I am new to AngularJs and Typescript. I am trying to implement I18n. My resource bundles are lying in a remote server. I use $translateProvider.useLoader('TranlationFilesLoader',{}) where TranlationFilesLoader is a custom loader class.

TranlationFilesLoader class looks as follows:

export class TranlationFilesLoader  {
    public static $inject = ['$http', '$q' ];

    constructor( $http: ng.IHttpService , $q: ng.IQService, options: any ) {

      var deferred = $q.defer();
      var currentLocale = options.key;
      var proxyurl = '/content?locale='+currentLocale;
      var req = {
         method:'GET',
         url: proxyurl ,
         }
      };
      $http(req).then(
        function(result) {
          deferred.resolve(result.data);
        },
        function(){
          deferred.reject(options.key)
        }
      );
      return deferred.promise;
    }
  }

In the module config I write the following..

.config(function ($translateProvider : ng.translate.ITranslateProvider) {
    $translateProvider.useLoader('TranlationFilesLoader', {});
    $translateProvider.preferredLanguage('en_us');// is applied on first load
    $translateProvider.useLocalStorage();// saves selected language to localStorage
  })

I have also registered the factory by writing

.factory('TranlationFilesLoader', TranlationFilesLoader)

The Error I get is : Uncaught Error: [$injector:undef] Provider 'TranlationFilesLoader' must return a value from $get factory method.

Has anyone tried this yet? I am stuck at various points . Please help. Thanks

2

There are 2 answers

0
jsDeveloper On BEST ANSWER

A silly mistake was not allowing me to retrieve the value of options.

The working code is as follows.

export class TranslationFilesLoader  {

public static $inject = ['$http', '$q' ];

constructor( $http: ng.IHttpService , $q: ng.IQService) {

   return function (options) {
      var deferred = $q.defer();
      var currentLocale = options.key;
      var proxyurl = '/content?locale='+currentLocale;
      var req = {
         method:'GET',
         url: proxyurl ,
      };
     $http(req).then(
       function(result) {
         deferred.resolve(result.data);
       },
       function(){
        deferred.reject(options.key)
       }
     );
    return deferred.promise;
  }
}
1
basarat On

In order to use $translateProvider.useLoader('TranlationFilesLoader', {}); you must register the name TranlationFilesLoader with angular.

In your case do : .service('TranlationFilesLoader', TranlationFilesLoader ); at a relevant location in your code.