AngularJS - Controller将从Service(MVC Web API调用)返回的数据视为未定义

use*_*255 1 asp.net-web-api angularjs

我是AngularJS的新手,正在研究样品.在我的示例应用程序中,我有一个MVC Web api(从db返回一些数据),它将从Angular Services调用并将数据返回给Controller.问题是我正在获取服务成功方法中的数据,但在我的控制器中它始终显示未定义且视图中不显示任何内容.请参阅以下代码:

我的控制器代码:

app.controller('CustomerController', function ($scope, customerService) {    
    //Perform the initialization
    init();

    function init() {
        $scope.customers= customerService.getCustomers();        
    }   
});
Run Code Online (Sandbox Code Playgroud)

我的服务代码:

app.service('customerService', function ($http){
       this.getCustomers = function () {
        $http({
            method: 'GET',
            url: 'api/customer'           
        }).
    success(function (data, status, headers, config) {
        return data;
    }).
    error(function (data, status) {
        console.log("Request Failed");
    });

    }
});
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题.

ksi*_*ons 6

您的问题出在您的服务实施中.你不能简单地return data因为那是异步成功回调.

相反,您可能会返回一个承诺,然后在您的控制器中处理它:

app.service('customerService', function ($http, $q){
    this.getCustomers = function () {
        var deferred = $q.defer();
        $http({
            method: 'GET',
            url: 'api/customer'           
        })
        .success(function (data, status, headers, config) {
           // any required additional processing here
           q.resolve(data);
        })
        .error(function (data, status) {
           q.reject(data);
        });
        return deferred.promise;
    }
});
Run Code Online (Sandbox Code Playgroud)

当然,如果您不需要额外的处理,您也可以只返回$ http调用的结果(这也是一个承诺).

然后在你的控制器中:

app.controller('CustomerController', function ($scope, customerService) {    
    //Perform the initialization
    init();

    function init() {
        customerService.getCustomers()
            .then(function(data) {
               $scope.customers= data;
            }, function(error) {
               // error handling here
            });        
    }   
});
Run Code Online (Sandbox Code Playgroud)


Jos*_*eph 6

那是因为你的服务定义了函数getCustomers,但方法本身实际上并没有返回任何东西,它只是进行一次http调用.

您需要以类似的形式提供回调函数

$http.get('/api/customer').success(successCallback);
Run Code Online (Sandbox Code Playgroud)

然后让回调返回或将数据设置到您的控制器.要做到这一点,回调可能必须来自控制器本身.

或者更好的是,你可以使用一个承诺在它回来时处理回报.

承诺可能看起来像

app.service('customerService', function ($http, $q){
   this.getCustomers = function () {
       var deferred = $q.defer();
       $http({
           method: 'GET',
           url: 'api/customer'           
        }).
        success(function (data, status, headers, config) {
            deferred.resolve(data)
        }).
        error(function (data, status) {
            deferred.reject(data);
        });

        return deferred;
    }
});
Run Code Online (Sandbox Code Playgroud)