0

要解決我的問題,我已經瀏覽了不同網站上的許多文章,但沒有解決它。 我在寫一個簡單的AngularJS應用程序。我對Angular很陌生。我寫了一個調用$ http服務的工廠方法,它從web api獲取數據。 Web api運行良好,並按預期返回JSON對象。AngularJS - 無法使用工廠呼叫http serrvice

角碼

var app = angular.module("app", []) 
      .controller("controller", function ($scope, WebFactory) { 
       $scope.data = "data"; 
       $scope.error = "error"; 
       $scope.data=WebFactory.getData(); 

      }) 
      .factory("WebFactory", function ($http) { 
       var obj = {}; 

       obj.getData = function() 
       { 
        $http({ 
         method: "GET", 
         url: "http://localhost:37103/api/employee",      
        }).then(function success(response) { 
         return response.data; 
        }) 
        .then(function error(response) { 
         return response; 
        }); 
        return 'No data'; 
       } 
       return obj; 

      }); 

HTML代碼

<body ng-controller="controller"> 

data: {{data}} 
<br/> 
error: {{error}} 
<br /> 

我已經花了2天,但仍然不知道爲什麼它不工作。

+0

是你看到在控制檯的任何錯誤? – Sajeetharan

+0

嗨@Sajeetharan,我不能看到任何錯誤,它說「HTML1300:導航發生。」只要。 –

+0

你的getData方法沒有多大意義。 $ http()返回一個承諾,當你收到迴應時將被解析。它的異步調用。所以,從獲取數據中,無論如何你都會返回「無數據」。迴應時,您只需在回叫中處理它,但之後沒有任何迴應。 –

回答

1

嘗試這樣代替:

所有的
var app = angular.module("app", []) 
      .controller("controller", function ($scope, WebFactory) { 
       $scope.data = "data"; 
       $scope.error = "error"; 
       $scope.data = {} 
       WebFactory.getData().then(function success(response) { 
         $scope.data = response.data; 
        }); 
      }) 
      .factory("WebFactory", function ($http) { 
       var obj = {}; 

       obj.getData = function() 
       { 
        return $http({ 
         method: "GET", 
         url: "http://localhost:37103/api/employee",      
        }) 
       } 
       return obj; 
      }); 
+0

非常感謝你,弗拉基米爾。我已經得到你的解釋和它的工作:) –

0

首先,你錯過了一個ng-app聲明

其次,你是濫用然後回調。它接受三個參數:成功回調,錯誤回調,最終回調。 隨着第一個執行成功,它會執行總是返回響應的第二個回調,但我認爲它不是那樣的,你可以使用更容易使用的get函數。 它應該是:

$http.get("http://localhost:37103/api/employee").then(function(response){ 
    //Do something with successfull response 
}, 
    function(error){ //do something with the error}); 

查看文檔中關於promises

最後,你正在處理的承諾和異步代碼,但返回的響應或字符串,而不是與結果的承諾。所以的getData()應該是這樣的:

obj.getData = function(){ 
    return $http.get("http://localhost:37103/api/employee"); 
} 

和Controller使用,然後(成功,錯誤終於)回調,或者如果你想上的錯誤提供值/終於回調的服務,你應該使用$ q服務

obj.getData(){ 
var deferred = $q.defer(); 
$http.get(...).then(function(response){ 
     deferred.resolve(response.data); 
    }, 
    function(error){ 
     deferred.reject("No Data"); 
    }); 
    return deferred.promise; 
} 

當然,你必須提供$ q服務的WebFactory

+0

感謝您的回覆朋友,問題是與異步電話和弗拉基米爾提供的決議,並在我的工作很好。 –

+0

我提供的HTML只是頁面的一部分。謝謝 –