8

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

2 Answers 2

6

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

}]);
Sign up to request clarification or add additional context in comments.

3 Comments

Unless $rootScope.success is used outside of this call, it now seems unnecessary.
@DavinTryon have added a simplified version
@SimonStaton Hi , I need response data but my $http method keep skipping callback function any ideas
-1

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

4 Comments

What did I miss? Also you are checking $rootScope.success outside your asynchronous callback.
This won't work because $rootScope.success is checked before it is set.
I believe I answered his question about chaining the behaviors but thanks for the downvotes on that unrelated matter
My downvote was based on the fact that the original answer did not solve the OP's problem. Now, the answer is just a duplicate of @SimonStaton.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.