Search code examples
angularjsangular-resource

How return `$resource` promise response?


I require the user details for multiple areas. I tried to return the details using a generic function. But i am getting the result as undefined. i understand that, I require to use the $differed to get the reuslt. But I don't have any idea about my current scenario.

anyone help me here please?

here is my function:

$scope.currentUserInfo = function () {

        var userDetails;

        server.getProfile.get().$promise.then(function ( response ) {

            if( response.Message.toUpperCase().indexOf('SUCCESS') != -1) {

                return  userDetails = response;

            }

            return "Not able to get the user details this time"

        })

        return userDetails;

    }

$scope.currentUser =  $scope.currentUserInfo();
console.log( $scope.currentUser ) //undefined.



var function1 = function () {

    $scope.currentUserInfo(); //once user details available do further

     $scope.age = $scope.currentUser.age;

}

var function2 = function () {

    $scope.currentUserInfo(); //once user details available do further

    $scope.name = $scope.currentUser.name;

}

Solution

  • server.getProfile.get() is an asynchronous call. The return userDetails; line in $scope.currentUserInfo function will get executed even if the server.getProfile.get() call is not yet finish. Try this:

    $scope.currentUserInfo = function () {
    
        server.getProfile.get().$promise.then(function ( response ) {
    
            if( response.Message.toUpperCase().indexOf('SUCCESS') != -1) {
    
                $scope.currentUser = response;
    
            }
    
            $scope.message =  "Not able to get the user details this time";
    
    
        })
    
    }
    

    $scope.currentUser will be populated after the ajax call is finish. I assume that you are using $scope.currentUser in your html bindings so when the value changes it will automatically reflect in your view