AngularJS - 无法使用工厂调用 http 服务

AngularJS - Unable to call http serrvice using factory

为了解决我的问题,我浏览了不同网站上的许多文章,但 none 解决了它。 我正在编写一个简单的 AngularJS 应用程序。我对 Angular 很陌生。我写了一个工厂方法,它调用 $http 服务从网络 api 获取数据。 Web api 运行 正常,并且按预期返回 JSON 对象。

Angular代码

 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天了,还是不知道为什么不行。

试试这样的方法:

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

首先,您缺少 ng-app 声明

其次,您误用了 then 回调。它接受三个参数:成功回调、错误回调、finally回调。 因为第一个然后执行成功,然后它执行第二个回调,总是 returns 响应,但我认为它不是那样的,你可以使用更易于使用的 get 函数。 应该是:

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

参见有关 promises

的文档

最后,您正在处理 promise 和异步代码,但返回响应或字符串而不是带有结果的 promise。所以 getData() 应该是这样的:

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

并在控制器中使用 then(success,error,finally) 回调,或者如果您想在服务中的 error/finally 回调中提供值,您应该使用 $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;
}

当然你必须向 WebFactory 提供 $q 服务