我正在尝试构建一个 Angular 服务,我可以重复使用它来执行我的 http 请求等。当它不在服务中时,这一切都有效。
以下代码可以运行并进行登录,但 $scope.data 的日志始终未定义。如果我在返回数据之前成功登录,它会返回数据,但不会返回到 Controller ,而这正是我真正想要做的。
为了澄清起见,我希望能够在我的 Controller 中成功访问从服务器返回的 json 数据作为“数据”。
//App.js
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function(url, options){
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
$http({
method: 'POST',
url: url,
data: xsrf,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
console.log(data);
return false;
});
}
})
Controller :
.controller('LoginCtrl', function ($scope, $stateParams, $location, $ionicLoading, $http, SaveSubmitService, $log) {
if (localStorage.getItem("SessionKey")) {
$location.path('home');
}
$scope.login = {};
$scope.doLogin = function doLogin() {
$scope.data = SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login);
$log.info($scope.data);
};
})
最佳答案
首先让SaveSubmitService
返回promise object .然后使用它的 API 提供一个回调,一旦数据被加载就执行:
.service('SaveSubmitService', function ($http, $log) {
this.addItem = function (url, options) {
var xsrf = $.param({
Username: options.Username,
Password: options.Password
});
return $http({
method: 'POST',
url: url,
data: xsrf,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
return response.data;
})
.catch(function(error) {
$log.error('ERROR:', error);
throw error;
});
}
});
然后您将在 Controller 中像这样使用它:
$scope.doLogin = function doLogin() {
SaveSubmitService.addItem('http://*****/Services/Account.asmx/Login', $scope.login).then(function(data) {
$scope.data = data;
$log.info($scope.data);
});
};
请注意,您如何返回 $http
函数调用的结果,它返回您在 Controller 中使用的 Promise。
关于javascript - Angular 服务 - 返回 http 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544750/