簡體   English   中英

javascript函數未返回未定義的值

[英]javascript function not returns undefined value

我有以下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調用的成功方法之前返回值。

有什么解決辦法嗎?

提前致謝。

您需要使用承諾。

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()函數將返回一個Promise,僅當Ajax調用完成時,才可以在控制器中使用它來更新$ scope.documents。

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

$ http的Angular返回promise的服務,因此您需要像這樣返回promise:

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

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM