我需要在下面的函数中打印出 localeData 值。 我知道如何在功能一侧打印,就像我在这里所做的那样。 我已经尝试过这个但没有成功。
$http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
console.log(localeData);
}).error(function(err) {
alert('warning', err.message);
});
//need to get that value here.
console.log(localeData);
编辑
其实我需要做的是这个
app.factory('customLoader', function($http, $q, SERVER_URL) {
return function(options) {
var deferred = $q.defer();
// do something with $http, $q and key to load localization files
$http.post(SERVER_URL + 'getLocaleData').success(function(localeData) {
//do something here to localData
}).error(function(err) {
alert('warning', err.message);
});
deferred.resolve(localeData);
return deferred.promise;
};
});
这就是我需要的。最后我需要发送 localeData。
最佳答案
您不需要自己创建和解决延迟。有一个更简单的方法。 (同样在您给出的示例中,您在底层ajax完成之前解析了promise)
Angular.js $http
服务也遵循 $q
接口(interface)!所以你可以写:
app.factory('customLoader', function($http, $q, SERVER_URL) {
return function(options) {
var promise = $http.post(SERVER_URL + 'getLocaleData')
.then(function(localeDataBag) {
var localeData = localeDataBag.data; // .data of 'then' equals to what .success returns.
modifiedLocaleData = localeData++; // do something here to localData
return modifiedLocaleData; // This is the new result
})
.catch(function(err) {
console.log(err);
return $q.reject(err); // This is the new result if something failed. Since we are chaining promises, we should keep failure state.
});
return promise;
};
});
关于javascript - Angularjs 在函数之外获取对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31513817/