我试图在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
}
};
})
但我不知道为什么我会收到这个错误:
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
如果我只是将呼叫this.translateUrl(language, translateUrlName);
移到translate: function(language, translateUrlName) {
之外,那么它可以正常工作,但我没有得到正确的行为。
答案 0 :(得分:2)
带有闭包的标准陷阱和Javascript中的this
。做:
return {
translate: function(language, translateUrlName) {
var self = this;
$translate.uses(language).then(function() {
self.translateUrl(language, translateUrlName);
});
},
translateUrl: function(language, translateUrlName) {
// do whatever
}
};
})
答案 1 :(得分:1)
将代码更改为
.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
};
})
最好使用命名函数,因为它们有助于调试......