javascript函数不返回未定义的值

javascript函数不返回未定义的值,javascript,angularjs,Javascript,Angularjs,我有以下angularjs函数: this.loadDocument = function() { var documents = []; alert("load documents"); $http({ url: 'http://localhost:8085/api/jsonws/dlapp/get-file-entries/repository-id

我有以下angularjs函数:

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; 
         };
我通过以下代码调用它:

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

    }
但函数的返回值未定义,因为它在ajax调用执行成功之前返回值

有什么解决办法吗


提前感谢。

$http角度服务返回承诺,因此您需要像这样返回承诺:

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)
        }
    });
然后你呼唤承诺,等待成功或失败:

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

 }

你需要使用承诺

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;
                    });
         };
loadDocument()函数现在返回一个承诺,只有在Ajax调用完成时,才能在控制器中使用该承诺更新$scope.documents

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

您可以出于某种原因传入回调。利用此机会,并在适当的回调中进行处理。可能的重复项应在
loadDocument
返回响应的末尾返回创建的承诺(来自$http服务)行是完全无用的,并且那里的注释是错误的
.success
,与
不同。那么
是不可链接的,因此此行实际上不会返回任何内容-您的
.success
在那里是无用的@NisargPujara@JsIsAwesome,很好,你改变了。现在,只需
返回response.data
即可获得实际的
文档
有效负载。完成后请告诉我,我将取消否决票。这是最短也是最好的方式。