Javascript 如何处理angularjs中的回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27816084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:42:40  来源:igfitidea点击:

How to handle callback in angularjs?

javascriptangularjscallback

提问by Hassaan

I have a registration mechanism in which rootscope variable is send via service. After success it updates the $rootScope.successfield. But the angularjs services is callback dependent.The service update the rootscope.success but the function sequentially execute the code.

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

How do i wait for service to complete its response and then further process?

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

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

And inside service

和内部服务

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

采纳答案by Simon Staton

You want to return your $httprequest from registerUser which can then be used in your controller in the same way you are using it in the service.

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

Controller:

控制器:

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

Service:

服务:

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


A few things worth noting...

有几点值得注意...

You are returning from a service which is not required, a service works as an instance and so the instance is already injected. It is a factory (singleton) that requires a return.

您正在从不需要的服务返回,服务作为实例工作,因此该实例已被注入。这是一个需要退货的工厂(单身)。

You are setting $scope.registrationto be the same as $rootScope.registrationand then setting $rootScope.registrationto be the same as $scope.registrationin your getEnterGeneratedCodefunction which is unnessasary and should be prototypicaly inherited anyway.

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

You should always try to defined depedencys with like so:

你应该总是尝试像这样定义依赖:

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

}]);

Unless $rootScope.successis being used elsewhere its currently pointless to set and I would recommend avoiding setting props on your $rootScope as it can quickly get out of control.

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

Here is a simplified version of your code:

这是您的代码的简化版本:

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

}]);

回答by Peter Ashwell

Use a promise - see changes below:

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

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

And inside service

和内部服务

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