如何在 angularjs 中处理回调

How to handle callback in angularjs?

本文关键字:处理 回调 angularjs      更新时间:2023-09-26

我有一个注册机制,其中根范围变量通过服务发送。成功后,它会更新$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;
})

您希望从 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设置为与getEnterGeneratedCode函数中的$scope.registration相同,这是不可分割的,无论如何都应该是原型继承的。

您应该始终尝试通过以下方式定义缺陷:

.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
        });
    };
}]);

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

.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;
})