Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle callback in angularjs?

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

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;
})
like image 547
Hassaan Avatar asked Jan 07 '15 09:01

Hassaan


People also ask

What is callback function in typescript?

A callback function is a function which is scheduled to be called after some asynchronous processing is completed. The callback functions are passed to another function as parameters which allows them to be called when the async processing is completed.


1 Answers

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

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.registration to be the same as $rootScope.registration and then setting $rootScope.registration to be the same as $scope.registration in your getEnterGeneratedCode function which is unnessasary and should be prototypicaly inherited anyway.

You should always try to defined depedencys with like so:

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

}]);

Unless $rootScope.success is 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.

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

}]);
like image 73
Simon Staton Avatar answered Sep 23 '22 03:09

Simon Staton