AngularJS - 无法使用工厂调用 http 服务 [英] AngularJS - Unable to call http serrvice using factory
本文介绍了AngularJS - 无法使用工厂调用 http 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了解决我的问题,我浏览了不同网站上的许多文章,但都没有解决.我正在编写一个简单的 AngularJS 应用程序.我对 Angular 很陌生.我编写了一个调用 $http 服务的工厂方法,该服务从 web api 获取数据.Web api 运行良好,并按预期返回 JSON 对象.
To resolve my issue I have gone through many articles on different sites, but none resolved it. I'm writing a simple AngularJS application. I'm quite new to Angular. I have written a factory method which call the $http service which gets the data from the web api. Web api is running fine and its returning the JSON object as expected.
角度代码
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 天了,但仍然不知道为什么它不起作用.
I have spent 2 days, but still dont know why its not working.
推荐答案
试试这样的:
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;
});
这篇关于AngularJS - 无法使用工厂调用 http 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文