要解決我的問題,我已經瀏覽了不同網站上的許多文章,但沒有解決它。 我在寫一個簡單的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天,但仍然不知道爲什麼它不工作。
是你看到在控制檯的任何錯誤? – Sajeetharan
嗨@Sajeetharan,我不能看到任何錯誤,它說「HTML1300:導航發生。」只要。 –
你的getData方法沒有多大意義。 $ http()返回一個承諾,當你收到迴應時將被解析。它的異步調用。所以,從獲取數據中,無論如何你都會返回「無數據」。迴應時,您只需在回叫中處理它,但之後沒有任何迴應。 –