【问题标题】:How to get data from Angularjs Service Response to Controller Scope Object如何从 Angularjs 服务响应中获取数据到控制器范围对象
【发布时间】:2019-10-10 11:09:03
【问题描述】:

我有简单的 Angularjs 1.7 应用程序。一切正常,我能够从 Web API 获取数据到 angularjs 服务。当我在 Angularjs 服务上进行调试时,我可以看到数据是通过 Web API 从数据库中获取的。所以我使用 angularjs 控制器中的服务将数据提取到范围对象中。但我不确定为什么没有在控制器范围对象中获取数据。有什么我缺少的东西来修复它。

Service.js

(function () {

    var app = angular.module('myApp');

    app.factory('websiteService', function ($http, $q) {
        var factory = [];
        var deferred = $q.defer();
        var baseURI = 'http://localhost:59029/api';

        factory.getAllStudents = function () {
            $http({
                method: 'GET',
                url: baseURI + '/Website/GetAllStudents'
            }).then(function (response) {
                deferred.resolve(response);
            }, function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        return factory;
    });
})();

Controller.js

(function () {

    var app = angular.module('myApp');

    app.controller('websiteController', ['$scope', '$http', 'websiteService', '$filter',
        function ($scope, $http, websiteService, $filter) {
            $scope.TestWebsite = "TestWebsite";
            console.log($scope.TestWebsite);

            //GET Students
            websiteService.getAllStudents()
                .then(function (response) {
                    $scope.FetchedAllStudents = response;
                    // NOT ABLE TO FETCH THE DATA HERE
                }, function (error) {
                    // error handling here
                });
        }
    ]);
})();

【问题讨论】:

  • 延迟 API 已经过时了。您可以简单地让getAllStudents() 返回$http.get(baseURI + '/Website/GetAllStudents'),其结果是一个承诺,并避免解决和拒绝的麻烦。
  • 所以在控制器websiteService.getAllStudents()中表示这样的@
  • 是的——无需更改您在控制器中处理服务调用的方式。虽然,即使有这种变化,我也看不出你为什么在 response 参数中没有得到任何东西。

标签: javascript angularjs asp.net-web-api


【解决方案1】:

没有必要用$q.defer 制造一个promise,因为$http 服务已经返回了一个promise:

app.factory('websiteService', function ($http, $q) {
    var factory = [];
    ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
    var baseURI = 'http://localhost:59029/api';

    factory.getAllStudents = function () {
        return $http({
            method: 'GET',
            url: baseURI + '/Website/GetAllStudents'
        }).then(function (response) {
            return response.data;
        });
    }
    return factory;
});

欲了解更多信息,请参阅Is this a "Deferred Antipattern"?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多