gpt4 book ai didi

javascript - AngularJS:无法读取未定义的属性 ''

转载 作者:行者123 更新时间:2023-11-30 12:27:29 24 4
gpt4 key购买 nike

我正在尝试在 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) { 之外,那么它可以工作,但我不知道没有得到正确的行为。

最佳答案

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

关于javascript - AngularJS:无法读取未定义的属性 '',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28896223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com