2015-03-19 155 views
0

我遇到以下angularjs功能:javascript函数不返回未定义值

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

    } 

但是从函数的返回值是undefined.because返回ajax调用执行成功之前的值。

有没有解决方法?

在此先感谢。

+0

您可以通过回调*出于某种原因*使用此机会,并在相应的回调中进行处理。的 – 2015-03-19 11:40:49

+0

可能重复[如何返回从异步调用的响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – JJJ 2015-03-19 11:40:56

回答

-1

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

} 
+0

你应该返回创建的承诺(从$ http服务)在'loadDocument'结尾 – mshaaban 2015-03-19 12:05:17

+0

是的,我知道,我forgat为此添加此感谢。 – Bazinga 2015-03-19 12:05:58

+0

'return response;'是完全无用的,注释有错误。 '.success'不像'.then',不像'.then'是不可链接的,所以这行不会实际返回任何东西 - 你的'.success'在那里没用。 @NisargPujara – 2015-03-19 13:38:07

0

您需要使用承诺。

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