AngularJS 服务延迟发送数据

AngularJS Service Delays to send the data

我正在获取服务中的数据,但我收到的数据为 未定义。我的 AngularJS 服务 returns 数据,但我收到的数据是 Undefined.

我的服务代码:

myApp.service("studentinfo", function ($http) {
  var studentlist = [];

  this.GetStudentList = function () {

    $.getJSON("/Home/GetStudentsList", function (data) {
      if (data.Result == "OK") {
        studentlist = data.Data;
      }
      else {
        studentlist = [];
      }
    }).complete(function() {
      return studentlist;
    });
  };
});

我的控制器代码:

myApp.controller("studentcontroller", function ($scope, $http, studentinfo) {
  $scope.StudentList = [];

  function LoadStudentRecord(){
    $scope.StudentList = studentinfo.GetStudentList();
  }

  LoadStudentRecord();
});

我看到你注入了 $http 但你没有使用它。用 $http 替换 jQuery 方法。 $http 将 return 一个承诺,在控制器中你可以使用任何承诺方法更新你的模型(然后,捕获,最后)

如前所述,您在这里混淆了一些东西:

  1. 您似乎正在使用 jQuery ( $.getJSON )- 我建议您尽量使用 Angular $http (顺便说一句).所以尝试使用 $http.GET ( https://docs.angularjs.org/api/ng/service/$http ).
  2. 请记住,这 return 是一个承诺。您可能确实希望 return 来自您的服务的承诺,以便您可以决定如何在您的控制器中处理失败的情况。
  3. 我建议使用不同的方式来实例化您的服务和控制器,请参阅下面的示例。这允许您稍后缩小代码。

代码:

var app = angular.module('myapp', []);
app.service('studentservice', ['$http', function ($http) {
    getStudentList = function () {
        return $http.get('/Home/GetStudentsList');
    };
    return {
        getStudentList: getStudentList
    }
}]);

app.controller('studentcontroller', ['$scope', 'studentservice', function ($scope, studentservice) {
    $scope.StudentList = [];

    function LoadStudentRecord() {
        $scope.StudentList = studentservice.getStudentList()
            .success(function (data, status, headers, config) {
                 $scope.StudentList = data;
        })
            .error(function (data, status, headers, config) {
                 console.log(data)
        });
    }
    LoadStudentRecord();
}]);
function studentFunction ($http) {
  var studentlist = [];
  this.GetStudentList = function () {
     return $http.get("/Home/GetStudentsList");
  };

}

myApp.service("studentinfo",  studentFunction);
myApp.controller("studentcontroller", function ($scope, studentinfo) {

  $scope.StudentList = [];

  function LoadStudentRecord(){
    studentinfo.GetStudentList().then(function (respoonse) {
    $scope.StudentList = respoonse;
  });
}

LoadStudentRecord();

});

服务应该看起来像那样。您在控制器中使用承诺。