简体   繁体   中英

javascript function not returns undefined value

i'm having following angularjs function :

this.loadDocument = function() { 
                var documents = [];
                 alert("load documents"); 
                $http({
                     url: 'http://localhost:8085/api/jsonws/dlapp/get-file-entries/repository-id/10182/folder-id/0',
                     method: 'get',             
                     headers: {
                            "Authorization": this.makeAuth(this.username,this.password)
                     }
            }).success(
                    function(response) {
                        alert("sucess");                        
                        documents=response;
                    });
              return documents; 
         };

i called it from following code :

$scope.loadDocument = function() {
        $scope.documents=documentService.loadDocument();

    }

but return value from the function is undefined.because it returns value before success method of ajax call executing.

is there any solution?

Thanks in advance.

You need to use promises.

this.loadDocument = function() { 

        return $http({
                     url: 'http://localhost:8085/api/jsonws/dlapp/get-file-entries/repository-id/10182/folder-id/0',
                     method: 'get',             
                     headers: {
                            "Authorization": this.makeAuth(this.username,this.password)
                     }
            }).then(
                    function(response) {
                       return response;
                    });
         };

The loadDocument() function now returns a promise which you can use in your controller to update $scope.documents only when the Ajax call completes.

 $scope.loadDocument = function() {
           documentService.loadDocument().then(
                 function(result){
                 $scope.documents= result;
           }); 
 }

$http service of angular return a promise so you need to return promise like this:

this.loadDocument = function() {
    return $http({
        url: 'http://localhost:8085/api/jsonws/dlapp/get-file-entries/repository-id/10182/folder-id/0',
        method: 'get',
        headers: {
            "Authorization": this.makeAuth(this.username, this.password)
        }
    });

Then you call the promise and wait for success or fail:

    $scope.loadDocument = function() {
       documentService.loadDocument().then(function(response){
          //the promise success
          $scope.documents = response.data;
       }).catch(function(err) {
          //the promise failed
       })

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM