我有以下服务
module.service('translationService', [
"$resource",
function($resource) {
var This = this;
This.params = 'HELLO';
This.getTranslation = function() {
var languageFilePath = 'sample.json';
//return languageFilePath;
$resource(languageFilePath).get(function(data) {
var temp = "";
if (This.params != "") {
angular.forEach(data, function(key, value) {
if (value == This.params)
temp = key;
});
} else {
This.translation = "Pls input key";
}
This.translation = temp;
return temp;
});
}
}
]);
在控制器中,我正在呼叫服务,
This.translate = translationService.getTranslation();
问题是当我调试temp有值时,但是当我返回值变为null时。可能是它内部的另一个函数.get()
并且返回正在失去范围。但是如果我按照上面的评论(languageFilePath
)返回//return languageFilePath;
,则值将传递给控制器。
请帮助我如何回报价值。
答案 0 :(得分:1)
转换getTranslation()
方法以返回承诺。
module.service('translationService', [ '$q', '$resource', translationService ]);
function translationService ($q, $resource) {
var This = this;
This.params = 'HELLO';
This.getTranslation = getTranslation;
function getTranslation () {
var deferred = $q.defer(),
languageFilePath = 'sample.json';
$resource(languageFilePath)
.get(_onGetTranslationSuccess, deferred.reject);
function _onGetTranslationSuccess (data) {
var translation;
if (This.params === '') {
deferred.reject('Pls input key');
} else {
angular.forEach(data, function (key, value) {
if (value === This.params) {
translation = key;
}
});
if (angular.isDefined(translation)) {
This.translation = translation;
deferred.resolve(translation);
} else {
deferred.reject('Translation not found');
}
}
}
return deferred.promise;
}
}
然后,您可以在控制器中使用承诺并获得翻译。
translationService.getTranslation().then(function (translation) {
This.translate = translation;
});
答案 1 :(得分:0)
您可以处理服务中的变量,然后声明一个函数以从控制器中检索值:
.service('translationService', function($q, $http, ...) {
var result= '';
...
function someFunction(...) {
...
result='translation';
...
}
...
return {
getTranslation: function() {return result;}
};
})
在控制器上,你可以这样做:
var res = translationService.getTranslation();
答案 2 :(得分:-1)
您必须从$ resource函数返回值。
python manage.py makemigrations polls