简体   繁体   中英

AngularJS: Cannot read property '' of undefined

I´m trying to do something like this in AngularJS:

.factory('TranslationService', function($location, $rootScope, $routeParams, $translate, $window, tmhDynamicLocale, 
                                            LocationService, MetaService) {
      return {
        translate: function(language, translateUrlName) {

            $translate.uses(language).then(function() {

                this.translateUrl(language, translateUrlName);
            });
         },
         translateUrl: function(language, translateUrlName) {
            // do whatever
        }
      };     
    })

But I don´t know why I´m getting this error:

TypeError: Cannot read property 'translateUrl' of undefined
    at services.js:1117
    at deferred.promise.then.wrappedCallback (angular.js:6846)
    at angular.js:6883
    at Object.$get.Scope.$eval (angular.js:8057)
    at Object.$get.Scope.$digest (angular.js:7922)
    at Object.$get.Scope.$apply (angular.js:8143)
    at done (angular.js:9170)
    at completeRequest (angular.js:9333)
    at XMLHttpRequest.xhr.onreadystatechange (angular.js:9303)angular.js:5754 (anonymous function)angular.js:4846 $getangular.js:6848 deferred.promise.then.wrappedCallbackangular.js:6883 (anonymous function)angular.js:8057 $get.Scope.$evalangular.js:7922 $get.Scope.$digestangular.js:8143 $get.Scope.$applyangular.js:9170 doneangular.js:9333 completeRequestangular.js:9303 xhr.onreadystatechange

If I just move the call this.translateUrl(language, translateUrlName); outside of translate: function(language, translateUrlName) { then it works, but I don´t get the correct behavior.

The standard trap with closures and this in Javascript. Do:

  return {
    translate: function(language, translateUrlName) {
        var self = this;

        $translate.uses(language).then(function() {
            self.translateUrl(language, translateUrlName);
        });
     },
     translateUrl: function(language, translateUrlName) {
        // do whatever
    }
  };     
})

change the code to

.factory('TranslationService', function($location, $rootScope, $routeParams, 
         $translate, $window, tmhDynamicLocale, LocationService, MetaService) {

    function translateUrl(language, translateUrlName) {
            // do whatever
        }

      function translate(language, translateUrlName) {

            $translate.uses(language).then(function() {

                translateUrl(language, translateUrlName);
            });
         }

      return {
        translate: translate,
         translateUrl: translateUrl
      };     
    })

its better to use named functions, as they do help in debugging...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM