如何处理angularjs中的回调?

时间:2015-01-07 09:23:09

标签: javascript angularjs callback

我有一个注册机制,其中的rootscope变量通过服务发送。成功后,它会更新$rootScope.success字段。但angularjs服务依赖于回调。服务更新了rootscope.success,但函数顺序执行代码。

我如何等待服务完成其响应然后进一步处理?

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) {

    $rootScope.success = false;
    $scope.registration = $rootScope.registration;

$scope.getEnterGeneratedCode = function(){
        $rootScope.registration = $scope.registration;
        registerUser.registerUser();
        if($rootScope.success){
           $location.path('/confirm');
        }
}

内部服务

.service('registerUser',function($http,$rootScope,$ionicLoading){
    this.registerUser = function(){
        $ionicLoading.show();
        $http({
            method: 'POST',
            datatype:'json',
            data:{obj:$rootScope.registration},
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        }).success(function (data, status, headers, config){
            if (status == '200') {
                var obj = data;
                $rootScope.success = true;
                $ionicLoading.hide();
                //alert(obj);
            }
        }).error(function (data, status, headers, config){
            $ionicLoading.hide();
        });
    };

 return this;
})

2 个答案:

答案 0 :(得分:6)

您希望从registerUser返回$http请求,然后可以在您的控制器中使用该请求,就像在服务中使用它一样。

控制器:

registerUser.registerUser().success(function(data, status, headers, config){
   //This code will now execute when the $http request has resolved with a success
   if($rootScope.success){
      $location.path('/confirm');
   }
}).error(function(error, status, headers, config){
   //An error occurred in $http request
   console.log(error); 
});

服务:

this.registerUser = function(){
    $ionicLoading.show();
    return $http({
        method: 'POST',
        datatype:'json',
        data:{obj:$rootScope.registration},
        url: 'http://localhost/LoginService.asmx/CreateUser',
        contentType: "application/json; charset=utf-8",
        cache: false
    }).success(function (data, status, headers, config){
        if (status == '200') {
            var obj = data;
            $rootScope.success = true;
            $ionicLoading.hide();
            //alert(obj);
        }
    }).error(function (data, status, headers, config){
        $ionicLoading.hide();
    });
};

值得注意的一些事情......

您从不需要的服务返回,服务作为实例工作,因此实例已经注入。这是一个需要返回的工厂(单身人士)。

您将$scope.registration设置为与$rootScope.registration相同,然后将$rootScope.registration设置为$scope.registration函数中的getEnterGeneratedCode相同,这是不合理的无论如何应该是原型继承的。

你应该总是尝试用这样的方式定义depedencys:

.controller('RegisterAccountCtrl', ['$scope', '$rootScope', 'registerUser', '$location', function($scope, $rootScope, registerUser, $location){

}]);

除非在其他地方使用$rootScope.success,否则它目前无意义设置,我建议避免在$ rootScope上设置道具,因为它很快就会失控。

以下是您的代码的简化版本:

.controller('RegisterAccountCtrl', [
    '$scope',
    '$rootScope',
    'registerUser',
    '$location',
function($scope, $rootScope, registerUser, $location) {

    $scope.getEnterGeneratedCode = function() {
        $ionicLoading.show();
        registerUser.registerUser().success(function(data, status, headers, config) {
            if (status == '200') {
                var obj = data;
                $ionicLoading.hide();
                $location.path('/confirm');
                //alert(obj);
            }
        }).error(function(data, status, headers, config) {
            $ionicLoading.hide();
        });

    }

}])

.service('registerUser', [
    '$http',
    '$rootScope',
    '$ionicLoading',
function($http, $rootScope, $ionicLoading) {

    this.registerUser = function() {
        return $http({
            method: 'POST',
            datatype: 'json',
            data: {
                obj: $rootScope.registration
            },
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        });
    };

}]);

答案 1 :(得分:-1)

使用承诺 - 请参阅以下更改:

.controller('RegisterAccountCtrl', function ($scope,$rootScope,registerUser,$location) {

    $rootScope.success = false;
    $scope.registration = $rootScope.registration;

$scope.getEnterGeneratedCode = function(){
        $rootScope.registration = $scope.registration;
        registerUser.registerUser().then(function() {
          $location.path('/confirm');
        })
}

内部服务

.service('registerUser',function($http,$rootScope,$ionicLoading){
    this.registerUser = function(){
        $ionicLoading.show();
        // Return a promise
        return $http({
            method: 'POST',
            datatype:'json',
            data:{obj:$rootScope.registration},
            url: 'http://localhost/LoginService.asmx/CreateUser',
            contentType: "application/json; charset=utf-8",
            cache: false
        }).success(function (data, status, headers, config){
            if (status == '200') {
                var obj = data;
                // Don't need now - $rootScope.success = true;
                $ionicLoading.hide();
                //alert(obj);
            }
        }).error(function (data, status, headers, config){
            $ionicLoading.hide();
        });
    };

 return this;
})