AngularJS Factory我做错了

时间:2014-06-02 18:49:16

标签: angularjs

我正在尝试为我的WebApiCall写一个工厂

所以我写了这个:

mod.factory('AccountService', function($http) {
var service = {};

var onError = function(response) {
    if (response == '') {
        return ['Timeout Occured !'];
    }
    var errors = [];
    for (var key in response.ModelState) {
        for (var i = 0; i < response.ModelState[key].length; i++) {
            errors.push(response.ModelState[key][i]);
        }
    }

    return errors;
};

var onSuccess = function(response) {
    return true;
}

service.Login = function(credentials) {
    $http.put('http://localhost:9239/Api/Account/', credentials).success(function(data) {
        return onSuccess(response);
    }).error(function (response) {
        return onError(response);
    });
};

return service;

});

控制器:

mod.controller('accountCtrl', function ($scope, $http, $window, $location, ConfigService, AccountService) {

$scope.credentials = { username: '', password: '' };
$scope.Errors = [];
$scope.registerModel = { username: '', password: '', passwordrepeat: '', email: '', emailrepeat: '' };
$scope.isLoading = false;

$scope.Login = function () {
    $scope.Errors = [];
    $scope.isLoading = true;
    AccountService.Login($scope.credentials).onSuccess(function(response) {
        $window.sessionStorage.setItem('loginToken', data.SuccessMessages[0]);
                   if (data.SuccessMessages[1] != '') {
                        $window.sessionStorage.setItem('groupId', data.SuccessMessages[1]);
                   }
                   $scope.isLoading = false;
                    $location.path('/Home');
    }).onError(function(errors) {
        $scope.Errors.push(errors);
        $scope.isLoading = false;
    });

当我登录登录MEthod时,确定。但是,如果调用$ http中的成功或错误方法,则它不会返回我的onSuccess或onError函数。

我觉得我犯了一些错误?

1 个答案:

答案 0 :(得分:0)

有些事情,$http承诺没有onSuccessonError回调,而是sucesserror。在您的服务中,您没有返回$http承诺,然后您就致电sucesserror,当然它不会起作用! $http调用,就像Ajax调用异步发生一样,这意味着你不能简单地在成功/错误回调中返回一个值,但是你可以返回一个承诺:

service.Login = function(credentials) {
    return $http.put('http://localhost:9239/Api/Account/', credentials)
};

并且在你的控制器中你可以使用它:

AccountService.Login($scope.credentials).then(function(data) {//success callback
   $window.sessionStorage.setItem('loginToken', data.SuccessMessages[0]);
    if (data.SuccessMessages[1] != '') {
       $window.sessionStorage.setItem('groupId', data.SuccessMessages[1]);
    }
    $scope.isLoading = false;
    $location.path('/Home');
},function(errors) {//error callback
    $scope.Errors.push(errors);
    $scope.isLoading = false;
})

当你在promise上调用它时,它会在promise被解析时执行,第一个函数是成功回调,第二个函数是错误回调。